Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Curs c(cork), Lecture notes of Computer Engineering and Programming

c program - c program

Typology: Lecture notes

2014/2015

Uploaded on 06/29/2015

sharath_kumar1
sharath_kumar1 🇮🇳

1 document

1 / 112

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Roinn na Matamaitice Feidhmí
Coláiste na hOllscoile Corcaigh
A Course in C Programming
Diarmuid O' Ríordáin, BE, MEngSc, MIEI
Department of Applied Mathematics
University College Cork
6th Revision - luned ì giugno 29, 201 5
1
F 0
8 6
File I/O is not covered until Chapter 8 so this section should be put
aside until later.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Curs c(cork) and more Lecture notes Computer Engineering and Programming in PDF only on Docsity!

Roinn na Matamaitice Feidhmí

Coláiste na hOllscoile Corcaigh

A Course in C Programming

Diarmuid O' Ríordáin, BE, MEngSc, MIEI

Department of Applied Mathematics

University College Cork

6th Revision - lunedì giugno 29, 2015

F 0

8 6 File I/O is not covered until Chapter 8 so this section should be put

aside until later.

  • 1 Introduction............................................................................................................
    • 1.11.1 Origin of C.........................................................................................................
  • 2.2 Why use C ?............................................................................................................. - 1 1.2 The “Hello World” Program............................................................................... - 1.21.3 The C Programming Environment..................................................................... 1.1..................................................................................................................................
  • 1 Chapter 2.................................................................................................................
    • 1.1 Variables, Data Types, I/O and Operators...........................................................
      • 1.1.1 2.1 Basic Data Types...................................................................................
  • 1.1.1.1 Modifying Basic Types............................................................................................ - 1.1. - 1.1.3 2.2 Variables................................................................................................
  • 1.1.3.1 Variable Names........................................................................................................
  • 1.1.3.2 Initialising Variables.................................................................................................
  • 1.1.3.
  • 1.1.3.4 Storage Classes.........................................................................................................
  • 1.1.3.
  • 1.1.3.6 Constants.................................................................................................................. - 1.1.4 2.3 Console Input / Output..........................................................................
  • 1.1.4.1 printf()......................................................................................................................
  • 1.1.4.
  • 1.1.4.3 scanf()
  • 1.1.4.4 getchar() and putchar().............................................................................................
  • 1.1.4.5 _flushall().................................................................................................................
  • 1.1.4.
  • 1.1.4.7 getch() and getche().................................................................................................. - 1.1.5 2.4 Operators...............................................................................................
  • 1.1.5.1 Assignment Operator................................................................................................
  • 1.1.5.2 Arithmetic Operators................................................................................................
  • 1.1.5.
  • 1.1.5.4 Increment and Decrement Operators........................................................................
  • 1.1.5.5 Special Assignment Operators.................................................................................
  • 1.1.5.6 Relational Operators
  • 1.1.5.
  • 1.1.5.8 Logical Operators.....................................................................................................
  • 1.1.5.
  • 1.1.5.10Bitwise Operators.....................................................................................................
  • 1.1.5.12Implicit & Explicit Type Conversions 1.1.5.11..................................................................................................................................
  • 1.1.5.14Sizeof Operator........................................................................................................ 1.1.5.13..................................................................................................................................
  • 1.1.5.15Precedence of Operators........................................................................................... - 1.1.6 2.5 Type Overflow & Underflow................................................................ - 1.1. - 1.1. - 1.1.9 2.6 Exercises...............................................................................................
  • 2 Chapter 3.................................................................................................................
    • 2.1 Statements...............................................................................................................
      • 2.1.1 3.1 Expressions and Statements..................................................................
      • 2.1.2 3.2 Iteration Statements...............................................................................
  • 2.1.2.1 for statement
  • 2.1.2.2 while statement.........................................................................................................
  • 2.1.2.3 do while....................................................................................................................
  • 2.1.2.
  • 2.1.2.
  • 2.1.2.6 break statement.........................................................................................................
  • 2.1.2.7 continue statement.................................................................................................... - 2.1. - 2.1.4 3.3 Decision Statements..............................................................................
  • 2.1.4.
  • 2.1.4.2 if statement
  • 2.1.4.3 Conditional Operator :- ?:.......................................................................................
  • 2.1.4.4 The switch Statement............................................................................................... - 2.1.5 3.4 Efficiency Considerations.....................................................................
  • 2.1.5.
  • 2.1.5.2 Unnecessary Type Conversions................................................................................
  • 2.1.5.3 Unnecessary Arithmetic - 2.1.6 3.5 Exercises...............................................................................................
  • 3 Chapter 4.................................................................................................................
    • 3.1 Functions.................................................................................................................
      • 3.1.1 4.1 Function Prototype ( declaration)..........................................................
      • 3.1.
      • 3.1.3 4.2 Function Definition & Local Variables................................................
  • 3.1.3.1 Static Local Variables............................................................................................... - 3.1.4 4.3 Scope Rules........................................................................................... - 3.1.5 4.4 Returning a Value - 3.1. - 3.1.7 4.5 Function Arguments - 3.1.8 4.6 Recursion............................................................................................... - 3.1. - 3.1.10 4.7 #define directive....................................................................................
  • 3.1.10.1Macros...................................................................................................................... - 3.1.11 4.8 Efficiency Considerations..................................................................... - 3.1.12 4.9 Exercises...............................................................................................
  • 4 Chapter 5.................................................................................................................
    • 4.1 Arrays & Strings....................................................................................................
      • 4.1.1 5.1 Single Dimension Arrays......................................................................
  • 4.1.1.1 Initialising Arrays..................................................................................................... - 4.1.2 5.2 Strings...................................................................................................
  • 4.1.2.
  • 4.1.2.2 Manipulating Strings................................................................................................ - 4.1.3 5.3 Multidimensional Arrays....................................................................... - 4.1. - 4.1.5 5.4 Arrays of Strings................................................................................... - 4.1. - 4.1.7 5.5 Arrays as arguments to functions ( 1D )................................................ - 4.1.8 5.6 Passing Multidimensional Arrays......................................................... - 4.1.9 5.7 Exercises...............................................................................................
  • 5 Chapter 6.................................................................................................................
    • 5.1 Pointers....................................................................................................................
      • 5.1.1 6.1 Pointer Variables...................................................................................
      • 5.1.2 6.2 Pointer Operators * and &...................................................................
      • 5.1.3 6.3 Call by Reference..................................................................................
      • 5.1.4 6.4 Pointers and Arrays...............................................................................
      • 5.1.
      • 5.1.6 6.5 Pointer Arithmetic.................................................................................
  • 5.1.6.1 Strings and pointers - 5.1.7 6.6 Arrays of Pointers.................................................................................. - 5.1.8 6.7 Command Line Arguments................................................................... - 5.1.9 6.8 Dynamic Memory Allocation................................................................ - 5.1. - 5.1.11 6.9 Multiple Indirection -- Pointers to Pointers.......................................... - 5.1.12 6.10 Pointers to Functions........................................................................... - 5.1.13 6.11 Efficiency Considerations................................................................... - 5.1. - 5.1.15 6.12 Exercises.............................................................................................
  • 6 Chapter 7.................................................................................................................
    • 6.1 Structures & Unions...............................................................................................
      • 6.1.1 7.1 Structures...............................................................................................
  • 6.1.1.1 Defining Structures..................................................................................................
  • 6.1.1.2 Accessing Structure Elements..................................................................................
  • 6.1.1.3 Initialising Structures
  • 6.1.1.4 Structure Assignment...............................................................................................
  • 6.1.1.5 Creating more Complex Structures with Structures.................................................
  • 6.1.1.6 Structure Pointers.....................................................................................................
  • 6.1.1.7 Dynamic allocation of structures.............................................................................. - 6.1. - 6.1.3 7.2 Bit--Fields............................................................................................. - 6.1.4 7.3 Unions................................................................................................... - 6.1.5 7.4 Enumerations - 6.1.6 7.5 The typedef Keyword............................................................................ - 6.1.7 7.6 Linked Lists...........................................................................................
  • 6.1.7.1 Nodes or Self-Referential Structures........................................................................
  • 6.1.7.2 Connecting the Nodes..............................................................................................
  • 6.1.7.3 Operations on Linked Lists...................................................................................... - 6.1.8 7.7 Efficiency Considerations..................................................................... - 6.1.9 7.8 Exercises...............................................................................................
  • 7 Chapter 8................................................................................................................
    • 7.1 Standard File I/O....................................................................................................
      • 7.1.1 8.1 Stream I/O
  • 7.1.1.1 Text Streams.............................................................................................................
  • 7.1.1.2 Binary Streams.........................................................................................................
  • 7.1.1.
  • 7.1.1.4 Common File Functions...........................................................................................
  • 7.1.1.5 Opening and Closing Files
  • 7.1.1.6 Reading & Writing Characters.................................................................................
  • 7.1.1.7 Working with strings of text.....................................................................................
  • 7.1.1.8 Formatted I/O...........................................................................................................
  • 7.1.1.
  • 7.1.1.10fread() and fwrite()...................................................................................................
  • 7.1.1.12Random Access I/O.................................................................................................. 7.1.1.11.................................................................................................................................. - 7.1.2 8.2 Low -- Level I/O...................................................................................
    • 7.1.3 8.3 Exercises...............................................................................................
  • 8 APPENDIX A : ASCII Character Set...................................................................

1.2 The “Hello World” Program

A C program consists of one or more functions or code modules. These are essentially groups of instructions that are to be executed as a unit in a given order and that can be referenced by a unique name. Each C program must contain a main() function. This is the first function called when the program starts to run. Note that while "main" is not a C keyword and hence not reserved it should be used only in this context.

A C program is traditionally arranged in the following order but not strictly as a rule.

Function prototypes and global data declarations The main() function Function definitions

Consider first a simple C program which simply prints a line of text to the computer screen. This is traditionally the first C program you will see and is commonly called the “Hello World” program for obvious reasons.

#include <stdio.h>

void main() { /* This is how comments are implemented in C to comment out a block of text */ // or like this for a single line comment

printf( "Hello World\n" ) ;

As you can see this program consists of just one function the mandatory main function. The parentheses, ( ), after the word main indicate a function while the curly braces, { }, are used to denote a block of code -- in this case the sequence of instructions that make up the function.

Comments are contained within a /* ... */ pair in the case of a block comment or a double forward slash, //, may be used to comment out the remains of a single line of test.

The line printf("Hello World\n " ) ;

is the only C statement in the program and must be terminated by a semi-colon. The statement calls a function called printf which causes its argument, the string of

text within the quotation marks, to be printed to the screen. The characters \n are not printed as these characters are interpreted as special characters by the printf function in this case printing out a newline on the screen. These characters are called escape sequences in C and cause special actions to occur and are preceded always by the backslash character, .

All C compiler include a library of standard C functions such as printf which allow the programmer to carry out routine tasks such as I/O, maths operations, etc. but which are not part of the C language, the compiled C code merely being provided with the compiler in a standard form.

Header files must be included which contain prototypes for the standard library functions and declarations for the various variables or constants needed. These are normally denoted by a .h extension and are processed automatically by a program called the Preprocessor prior to the actual compilation of the C program.

The line #include <stdio.h>

instructs the preprocessor to include the file stdio.h into the program before compilation so that the definitions for the standard input/output functions including printf will be present for the compiler. The angle braces denote that the compiler should look in the default “INCLUDE” directory for this file. A pair of double quotes indicate that the compiler should search in the specified path e.g.

#include “d:\myfile.h”

NB : C is case sensitive i.e. printf() and Printf() would be regarded as two different functions.

1.3 The C Programming Environment

Program development is nowadays carried out in specifically designed software systems or workbenches with editing, compilation, linking, debugging and execution facilities built in. In this course we will be making use of a Microsoft system but the features found in this are to be found in one form or another in almost all modern systems.

The first phase of development involves the creation and editing of a file containing the appropriate C instructions which will be stored using a file extension of .c normally to invoke the C compiler, e.g. fname.c.

The next step is to take the C program and to compile it into object code or machine language code. The C compiler includes the aforementioned preprocessor which is called automatically before the code translation takes place. This preprocessor acts on special commands or directives from the programmer to manipulate the text of the C code before compilation commences. These directives might involve including other source files in the file to be compiled, replacing special symbols with specific replacement text, etc. Once this is done the C code is translated into object code and stored in a file with the extension .obj , e.g. fname.obj.

The final phase in building the executable program is called linking. After the compilation stage the C code has been translated into machine recognisable code but is in a somewhat unconnected state. The program invariably contains references to standard library functions or functions contained in other libraries or modules which must be connected to the C program at link time. This simply involves linking the machine code for these functions with the program’s object code to complete the build process and produce an executable file with an extension .exe e.g. fname.exe.

The executable program can be loaded and run from within the programming environment itself or may be run from the host environment directly. If it executes as expected that is the end of the task. However if this does not happen it may require the use of the debugger to isolate any logical problems. The debugger allows us to step through the code instruction by instruction or up to predefined break-points and to look at the values of variables in the code in order to establish where errors are introduced.

NB : Note that the keyword int may be omitted without error so that the type unsigned is the same as type unsigned int , the type long is equivalent to the type long int, and the type short is equivalent to the type short int.

2.2 Variables

A variable is a named piece of memory which is used to hold a value which may be modified by the program. A variable thus has three attributes that are of interest to us : its type, its value and its address.

The variable’s type informs us what type and range of values it can represent and how much memory is used to store that value. The variable’s address informs us where in memory the variable is located (which will become increasingly important when we discuss pointers later on).

All C variables must be declared as follows :- type variable-list ; For Example :- int i ; char a, b, ch ;

Variables are declared in three general areas in a C program.

When declared inside functions as follows they are termed local variables and are visible (or accessible) within the function ( or code block ) only.

void main() { int i, j ; ... }

A local variable is created i.e. allocated memory for storage upon entry into the code block in which it is declared and is destroyed i.e. its memory is released on exit. This means that values cannot be stored in these variables for use in any subsequent calls to the function.

When declared outside functions they are termed global variables and are visible throughout the file or have file scope. These variables are created at program start-up and can be used for the lifetime of the program.

int i ; void main() { ... } When declared within the braces of a function they are termed the formal parameters of the function as we will see later on.

int func1( int a, char b ) ;

Variable Names

Names of variables and functions in C are called identifiers and are case sensitive. The first character of an identifier must be either a letter or an underscore while the remaining characters may be letters, numbers, or underscores. Identifiers in C can be up to 31 characters in length.

Initialising Variables

When variables are declared in a program it just means that an appropriate amount of memory is allocated to them for their exclusive use. This memory however is not initialised to zero or to any other value automatically and so will contain random values unless specifically initialised before use.

Syntax :- type var-name = constant ;

For Example :- char ch = 'a' ; double d = 12.2323 ; int i, j = 20 ; /* note in this case i is not initialised */

Storage Classes

There are four storage class modifiers used in C which determine an identifier’s storage duration and scope. auto static register extern

An identifier’s storage duration is the period during which that identifier exists in memory. Some identifiers exist for a short time only, some are repeatedly created and destroyed and some exist for the entire duration of the program. An identifier’s scope specifies what sections of code it is accessible from.

The auto storage class is implicitly the default storage class used and simply specifies a normal local variable which is visible within its own code block only and which is created and destroyed automatically upon entry and exit respectively from the code block. The register storage class also specifies a normal local variable but it also requests that the compiler store a variable so that it may be accessed as quickly as possible, possibly from a CPU register. The static storage class causes a local variable to become permanent within its own code block i.e. it retains its memory space and hence its value between function calls.

When applied to global variables the static modifier causes them to be visible only within the physical source file that contains them i.e. to have file scope. Whereas the extern modifier which is the implicit default for global variables enables them to be accessed in more than one source file. For example in the case where there are two C source code files to be compiled together to give one executable and where one specific global variable needs to be used by both the extern class allows the programmer to inform the compiler of the existence of this global variable in both files.

2.3 Console Input / Output

This section introduces some of the more common input and output functions provided in the C standard library.

printf()

The printf() function is used for formatted output and uses a control string which is made up of a series of format specifiers to govern how it prints out the values of the variables or constants required. The more common format specifiers are given below

%c character %f floating point %d signed integer %lf double floating point %i signed integer %e exponential notation %u unsigned integer %s string %ld signed long %x unsigned hexadecimal %lu unsigned long %o unsigned octal %% prints a % sign

For Example :- int i ;

printf( "%d", i ) ;

The printf() function takes a variable number of arguments. In the above example two arguments are required, the format string and the variable i. The value of i is substituted for the format specifier %d which simply specifies how the value is to be displayed, in this case as a signed integer.

Some further examples :-

int i = 10, j = 20 ; char ch = 'a' ; double f = 23421.2345 ;

printf( "%d + %d", i, j ) ; /* values are substituted from the variable list in order as required */ printf( "%c", ch ) ;

printf( "%s", "Hello World\n" ) ;

printf( "The value of f is : %lf", f ) ;/*Output as : 23421. / printf( "f in exponential form : %e", f ) ; / Output as : 2.34212345e+

Field Width Specifiers

Field width specifiers are used in the control string to format the numbers or characters output appropriately.

Syntax :- %[total width printed][.decimal places printed]format specifier

where square braces indicate optional arguments.

For Example :- int i = 15 ; float f = 13.3576 ; printf( "%3d", i ) ; /* prints "_15 " where _ indicates a space character / printf( "%6.2f", f ) ; / prints "_13.36" which has a total width of 6 and displays 2 decimal places / printf( “%.f”, 6,2,f ) ; / prints "_13.36" as above. Here

  • is used as replacement character for field widths */

There are also a number of flags that can be used in conjunction with field width specifiers to modify the output format. These are placed directly after the % sign. A - (minus sign) causes the output to be left-justified within the specified field, a + (plus sign) displays a plus sign preceding positive values and a minus preceding negative values, and a 0 (zero) causes a field to be padded using zeros rather than space characters.

scanf()

This function is similar to the printf function except that it is used for formatted input. The format specifiers have the same meaning as for printf() and the space character or the newline character are normally used as delimiters between different inputs.

For Example :- int i, d ; char c ; float f ;

scanf( "%d", &i ) ;

scanf( "%d %c %f", &d, &c, &f ) ; /* e.g. type "10_x_1.234 ret " */

scanf( "%d:%c", &i, &c ) ; /* e.g. type "10:x ret " */

The & character is the address of operator in C, it returns the address in memory of the variable it acts on. (Aside : This is because C functions are nominally call--by--value. Thus in order to change the value of a calling parameter we must tell the function exactly where the variable resides in memory and so allow the function to alter it directly rather than to uselessly alter a copy of it. )

Note that while the space and newline characters are normally used as delimiters between input fields the actual delimiters specified in the format string of the scanf statement must be reproduced at the keyboard faithfully as in the case of the last sample call. If this is not done the program can produce somewhat erratic results!

The scanf function has a return value which represents the number of fields it was able to convert successfully.

For Example :- num = scanf( “%c %d”, &ch, &i );

This scanf call requires two fields, a character and an integer, to be read in so the value placed in num after the call should be 2 if this was successful. However if the input was “a bc” then the

These functions perform the same operation as getchar() except that they are unbuffered input functions i.e. it is not necessary to type ret to cause the values to be read into the program they are read in immediately the key is pressed. getche() echoes the character hit to the screen while getch() does not.

For example :- char ch ; ch = getch() ;

2.4 Operators

One of the most important features of C is that it has a very rich set of built in operators including arithmetic, relational, logical, and bitwise operators.

Assignment Operator

int x ; x = 20 ;

Some common notation :- lvalue -- left hand side of an assignment operation rvalue -- right hand side of an assignment operation

Type Conversions :- the value of the right hand side of an assignment is converted to the type of the lvalue. This may sometimes yield compiler warnings if information is lost in the conversion.

For Example :- int x ; char ch ; float f ;

ch = x ; /* ch is assigned lower 8 bits of x, the remaining bits are discarded so we have a possible information loss / x = f ; / x is assigned non fractional part of f only within int range, information loss possible / f = x ; / value of x is converted to floating point */

Multiple assignments are possible to any degree in C, the assignment operator has right to left associativity which means that the rightmost expression is evaluated first.

For Example :- x = y = z = 100 ;

In this case the expression z = 100 is carried out first. This causes the value 100 to be placed in z with the value of the whole expression being 100 also. This expression value is then taken and assigned by the next assignment operator on the left i.e. x = y = ( z = 100 ) ;

Arithmetic Operators

      • / --- same rules as mathematics with * and / being evaluated before + and -. % -- modulus / remainder operator

For Example :- int a = 5, b = 2, x ; float c = 5.0, d = 2.0, f ;

x = a / b ; // integer division, x = 2. f = c / d ; // floating point division, f = 2.5. x = 5 % 2 ; // remainder operator, x = 1.

x = 7 + 3 * 6 / 2 - 1 ;// x=15,* and / evaluated ahead of

  • and -.

Note that parentheses may be used to clarify or modify the evaluation of expressions of any type in C in the same way as in normal arithmetic.

x = 7 + ( 3 * 6 / 2 ) - 1 ; // clarifies order of evaluation without penalty x = ( 7 + 3 ) * 6 / ( 2 - 1 ) ; // changes order of evaluation, x = 60 now.

Increment and Decrement Operators

There are two special unary operators in C, Increment ++, and Decrement -- , which cause the variable they act on to be incremented or decremented by 1 respectively.

For Example :- x++ ; /* equivalent to x = x + 1 ; */

++ and -- can be used in prefix or postfix notation. In prefix notation the value of the variable is either incremented or decremented and is then read while in postfix notation the value of the variable is read first and is then incremented or decremented.

For Example :- int i, j = 2 ;

i = ++ j ; /* prefix :- i has value 3, j has value 3 / i = j++ ; / postfix :- i has value 3, j has value 4 */

Special Assignment Operators

Many C operators can be combined with the assignment operator as shorthand notation

For Example :- x = x + 10 ; can be replaced by x += 10 ;

Similarly for -=, *=, /=, %=, etc.

this will give no compilation error to warn us but will compile and assign a value 10 to x when the condition is tested. As this value is non-zero the if condition is deemed true no matter what value x had originally. Obviously this is possibly a serious logical flaw in a program.

Bitwise Operators

These are special operators that act on char or int arguments only. They allow the programmer to get closer to the machine level by operating at bit-level in their arguments.

& Bitwise AND | Bitwise OR ^ Bitwise XOR ~ Ones Complement

Shift Right << Shift left

Recall that type char is one byte in size. This means it is made up of 8 distinct bits or binary digits normally designated as illustrated below with Bit 0 being the Least Significant Bit (LSB) and Bit 7 being the Most Significant Bit (MSB). The value represented below is 13 in decimal.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 0 0 0 0 1 1 0 1

An integer on a 16 bit OS is two bytes in size and so Bit 15 will be the MSB while on a 32 bit system the integer is four bytes in size with Bit 31 as the MSB.

Bitwise AND, &

RULE : If any two bits in the same bit position are set then the resultant bit in that position is set otherwise it is zero.

For Example :-

Bitwise OR, |

RULE : If either bit in corresponding positions are set the resultant bit in that position is set.

For Example :-

Bitwise XOR, ^

RULE : If the bits in corresponding positions are different then the resultant bit is set.

For Example :-

^ 0011 1100 (63)

Shift Operators, << and >>

RULE : These move all bits in the operand left or right by a specified number of places.

Syntax : variable << number of places variable >> number of places

For Example :- 2 << 2 = 8 i.e.

0000 0010 becomes 0000 1000

NB : shift left by one place multiplies by 2 shift right by one place divides by 2

Ones Complement

RULE : Reverses the state of each bit.

For Example :-

1101 0011 becomes 0010 1100

NB : With all of the above bitwise operators we must work with decimal, octal, or hexadecimal values as binary is not supported directly in C.

The bitwise operators are most commonly used in system level programming where individual bits of an integer will represent certain real life entities which are either on or off, one or zero. The programmer will need to be able to manipulate individual bits directly in these situations. A mask variable which allows us to ignore certain bit positions and concentrate the operation only on those of specific interest to us is almost always used in these situations. The value given to the mask variable depends on the operator being used and the result required.

For Example :- To clear bit 7 of a char variable.

char ch = 89 ; // any value

char mask = 127 ; // 0111 1111

ch = ch & mask ; // or ch &= mask ;

For Example :- To set bit 1 of an integer variable.

int i = 234 ; // any value

int mask = 2 ; // a 1 in bit position 2

i |= mask ;

Implicit & Explicit Type Conversions

Normally in mixed type expressions all operands are converted temporarily up to the type of the largest operand in the expression.