You are on page 1of 46

C Program Compilation Steps

You compile c program and get executables. Have you ever wondered what happens during
compilation process and how c program gets converted to executable?
In this module we will learn what are the stages involved in c program compilation using gcc
on Linux.
Normally C program building process involves four stages to get executable (.exe)
1. Preprocessing
2. Compilation
3. Assembly
4. Linking
The following Figure shows the steps involved in the process of building the C program
starting from the preprocessing until the loading of the executable image into the memory for
program running.

Compilation with gcc with different options


-E

Preprocess only; do not compile, assemble or link

-S

Compile only; do not assemble or link

-c

Compile and assemble, but do not link

-o <file> Place the output into <file>

We will use below hello.c program to expain all the 4 phases


#include<stdio.h>
//Line 1
#define MAX_AGE 21
//Line 2
int main()
{
printf( "Maximum age : %d ",MAX_AGE); //Line 5
}

1. Preprocessing
This is the very first stage through which a source code passes. In this stage the following
tasks are done:
1. Macro substitution
2. Comments are stripped off
3. Expansion of the included files
To understand preprocessing better, you can compile the above hello.c program using flag
E with gcc. This will generate the preprocessed hello.i
Example:
>gcc -E hello.c -o hello.i
//hello.i file content
# 1 "hello.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "hello.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 28 "/usr/include/stdio.h" 3 4

Truncated some text

extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__));


# 918 "/usr/include/stdio.h" 3 4
# 2 "hello.c" 2
int main()
{
printf( "Maximum age : %d ",21);
}

In above code (hello.i) you can see macros are substituted with its value (MA_AGE with 21
in printf statement), comments are stripped off (//Line 1, //Line 2 and //Line 5)and libraries
are expanded(<stdio.h>)

2. Compilation
Compilation is the second pass. It takes the output of the preprocessor (hello.i) and generates
assembler source code (hello.s)
> gcc -S hello.i -o hello.s
//hello.s file content
.file
.LC0:

"hello.c"
.section

.rodata

.string "Maximum age : %d "


.text
.globl main
.type
main, @function
main:
.LFB0:
.cfi_startproc
pushq
%rbp
.cfi_def_cfa_offset 16
movq
%rsp, %rbp
.cfi_offset 6, -16
.cfi_def_cfa_register 6
movl
$.LC0, %eax
movl
$21, %esi
movq
%rax, %rdi
movl
$0, %eax
call
printf
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size
main, .-main
.ident "GCC: (GNU) 4.4.2 20091027 (Red Hat 4.4.2-7)"
.section
.note.GNU-stack,"",@progbits

Above code is assembly code which assembler can understand and generate machine code.

3. Assembly

Assembly is the third stage of compilation. It takes the assembly source code (hello.s) and
produces an assembly listing with offsets. The assembler output is stored in an object file
(hello.o)
>gcc -c hello.s -o hello.o
Since the output of this stage is a machine level file (hello.o). So we cannot view the content
of it. If you still try to open the hello.o and view it, youll see something that is totally not
readable
//hello.o file content
^?ELF^B^A^A^@^@^@^@^@^@^@^@^@^A^@>^@^A^@^@^@^@^@^@^@^@^@^@^@^@^
@^@^@^@^@^@^@@^A^@^@^@^@^@^@^@^@^@^@@^@^@^@^@^@@^@^M^@^@UH<89>
^@^@^@^@^U^@^@^@H<89>^@^@^@^@^@^@^@^@^@^@^@Maximum age :%d
^@^@GCC:GNU)4.4.220091027(RedHat4.4.2-7)^@^@^T^@^@^@^@^@^@^@^AzR^
@^Ax^P^A^[^L^G^H<90>^A^@^@^\^@^@^@^\^@^@^@^@^@^@^@^]^@^@^@^@A^N^PC
<86>^B^M^FX^L^G^H^@^@^@^@.symtab^@.strtab^@.shstrtab^@.rela.text^@
.data^@.bss^@.rodata^@.comment^@.note.GNU-stack^@.rela.eh_frame^@
^@^@^@^@^@^@^@^@^@^@^

By looking at above code only thing we can explain is ELF (executable and linkable format).
This is a relatively new format for machine level object files and executable that are produced
by gcc.

4. Linking
Linking is the final stage of compilation. It takes one or more object files or libraries as input
and combines them to produce a single executable file (hello.exe). In doing so, it resolves
references to external symbols, assigns final addresses to procedures/functions and variables,
and revises code and data to reflect new addresses (a process called relocation).
> gcc hello.o -o hello
./hello
Maximum age : 21

Now you know c program compilation steps (Preprocessing, Compiling, Assembly, and
Linking). There is lot more things to explain in liking phase.

Your First C Program


In previous two sections we have learnt how to setup c environment and steps in c program
compilation. Now we are going to learn how to write a simple C program.
Type the following program into your favorite editor

//C simple program


#include<stdio.h
int main()
{
/* It prints Hello World */
printf( "Hello, World\n");
return 0;
}

Save it as hello.c, Compile and execute using following steps


gcc hello.c
./a.out
Hello, World

Let us look at various parts of above c program


1. The first line of program //C simple program is a single line comment. This line is
ignored by compiler.
2.

The Next line of the program #include <stdio.h> is a preprocessor command which
tells a C compiler to include stdio.h file before going to actual compilation. its called
as header file.

3. The next line int main() is the main function where program execution begins and int
is the return type of main function.
4. The next /*It prints Hello World */ is a multi line comment.
5. The next line printf(...) is another function available in C library which causes the
message "Hello, World" to be displayed on the screen.
6. The next line return 0; terminates main()function and returns the value 0.
C Data Types

In the C programming language, data types refers to an extensive system for declaring
variables or functions of different types. The type of a variable tells how much space it
occupies in storage and how the bit pattern stored is interpreted.

Types

Description

Basic types
1.

The C language provides four basic arithmetic type identifiers in C (char,


int, float and double) and optional specifiers (signed, unsigned, short,
long).

2. Enumerated

Enumeration data type consists of named integer constants as a list. It start

with 0(zero) by default and value is incremented by 1 for the sequential


identifiers in the list. example: enum

types
3. void type

The type specifier void indicates that no value is available.

4. Derived types Array, pointer, structure, union and function are called derived data type.
Character Types

'char' data type is used to store 1 character and it occupies 1 byte in storage.
Ex. char ch='A'
Here what gets stored in ch is binary equivalent of the ASCII value of 'A'(.i.e binary of 65)
char can be signed or unsigned. signed char is same as ordinary char.

Data Type

Storage Size

Value range

char

1 byte

-128 to +127

unsigned char

1 byte

0 to 255

Interger Types

This data type allows a variable to store numerical values. Range of an interger is compiler
dependent.
For example in 16 bit compiler like Tubo C, it is 2 bytes and for 32 bit compiler it is 4 bytes.
C offers a variation of the integer data type. Like short and long. short minimum size is 2
bytes and long minimum size is 4 bytes.

Data Type

Storage Size

Value range

int

4 bytes

-2,147,483,648 to 2,147,483,647

unsigned int

4 bytes

0 to 4,294,967,295

short

2 bytes

-32,768 to 32,767

unsigned short

2 bytes

0 to 65,535

long

4 bytes

-2,147,483,648 to 2,147,483,647

unsigned long

4 bytes

0 to 4,294,967,295

[Note : Sizes in above table are for 32 bit compiler]


Floating-point Types

Float data type allows a variable to store decimal values. A float occupies four bytes in
memory. If this is insufficient, then C offers a double datatype that occupies 8 bytes in
memory. If situation demands more then long double can be used. It occupies 10 bytes in
memory.

Data Type

Storage Size

Value range

Precision

float

4 bytes

1.2E-38 to 3.4E+38

6 decimal places

double

8 bytes

2.3E-308 to 1.7E+308

15 decimal places

long double

10 bytes

3.4E-4932 to 1.1E+4932

19 decimal places

void types

'void' is an empty data type or it specify that no value is available. In C we can use void in
three situations:
A. function return type as void
void main()
{
}

It indicates that main function doesn't return any value.


B. function arguments type as void
int fun(void)
{
}

It indicates that fun does not accept any parameter


C. A pointer variable type(void pointer)
void *p;

Here void* represents the address of variable, but not its type.

C Tokens and Keywords


In following diagram building blocks of the c program are shown.

1. Any symbol that is used while writing C program is called alphabets or characters
(Ex. A, b, c, +, *, i).
2. One or more alphabets can be grouped together to form meaningful words.These
meaningful words are tokens.
3. One or more tokens can be grouped together to form meaningful sentences. These
meaningful sentences are called statements or instructions.
4. One or more statements can be grouped together to form a complete program.

C Tokens

A token is the smallest or basic unit of a C program and one or more alphabets are grouped
together to form a tokens.
Example : if, for, while, sum, add, +, -, /, ++, +=, = etc.
Classification:
Keywords: if, for,, while, etc.
Identifiers: sum, name, i, etc.
Constants: 1, 1.5, 'A', "Hi", etc.
Operators: +, -, *, etc.
Special Symbols: [], {}, (), @, etc.

C Keywords
The tokens with predefined meaning in C language is called keywords. Keywords are
reserved for specific purpose hence it is also called reserved words.
We can not use keywords as a variable names because if we do so we are trying to assign new
meaning to already predefined words which is not allowed.
There are total 32 keywords in C.
auto

double

int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed

void

default

goto

sizeof

volatile

do

if

static

while

Note : Compiler vendors (like Microsoft, Borland, etc.) provide their own keyword apart
from mentioned above. For example near, far asm, etc..

C Constants

A constant is a value that does not change during execution of the program. A "constant" is a
number, character or character string that can be used in a program as a value.
C supports several types of constants

Integer constants

Real or Floating Point (Float) constants

Character constants

Integer constants
An integer constant can be decimal, hexadecimal or octal. Prefix specifies the base.
For Example :
12
99
OX1A
ox1a
o23
O22

/*Decimal*/
/*Decimal*/
/*Hexadecimal */
/*Hexadecimal */
/*Octal*/
/*Octal*/

An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
12
12l
12L
12u
12ul
12UL

/*int*/
/*long int*/
/*long int*/
/*unsigned int*/
/*unsigned long int*/
/*unsigned long int*/

Rules for Constrcting integer constant


1. Must have one or more digit without a decimal point.
2. Can be either positive or negative. If no sign precedes the constant, it is positive
3. No comma or blanks allowed within an integer constant
4. Integer constants are by default int.
Example of invalid integer constants:
1.5
5+
1,5

/*Not Valid*/
/*Not valid */
/*Not valid */

Real or Floating Point (Float) constants

A floating point constant has integer part, decimal and fractional part. A floating point
constant can also be represented in exponential form.
Example:
+123.50 /* 123 is decimal part, 50 is fractional part 8*/
-924.0
+3.42e-4 /* In fractional form : 0.000342 */
12.5E8

Rules for constructing floating point constants


1. It Must have at least one digit and only one decimal point.
2. It Can be either positive or negative. If no sign precedes the constant, it is positive.
3. No comma or blanks allowed within a floating constant.
4. In Exponential form, e can be either in lower case or upper case.
5. Floating-point constants default to type double.
6. By using the suffixes f or l (or F or L ), the constant can be specified as float or long
double, respectively.
Example :
1.1.1
1,1.1
5.4e5L
3.41E

/*Not
/*Not
/*Not
/*Not

valid
Valid
Valid
Valid

:
:
:
:

two decimal points*/


comma not allowed */
L not allowed in exponential form*/
no exponent after E*/

Character constants
A 'character constant' is a single alphabet, a single digit or a single special symbol enclosed
within single inverted commas.
Example : 'A' 'g' '1' '=' or '\t'
char datatype variables can be used to store character constants. The length of character
constant is always 1 byte.
Rules for constructing character constants
1. Single alphabet, digit or special symbol.
2. Should be enclosed within single inverted commas.
3. Since characters are internally treated as integers, the ASCII values of character is
what is stored internally.For example ASCII for A is 65.
4. Range : -128 to 127

5. Example: C,7, Escape sequence like \n

C Variables

A 'Variable' is a name given to a memory location and it's value may change during
program execution.

Each variable in C has a specific type, which determines the size and layout of the
variable's memory, the range of values that can be stored within that memory and the
set of operations that can be applied to the variable.
Example : int x = 10;

In above diagram x is a name given to the memory location whose address is 0X2001009 and
the type of value that can be stored at this memory location is integer constant .i.e 10.
Now x=20, this would overwrite the earlier value 10 because a memory location can hold
only one value at a time. Since the location whose name is x can hold different values at
different times, x is know as variable.

Rules of constructing variable names in C


1. A variable name is any combination of alphabets, digits or underscores of max size of
31 characters (Some compiler allow more than 31 characters but for safer side always
stick to 31 characters).
2. First character should not be a number. It can be alphabets or underscore.
3. No commas, blanks or any special symbols other than an underscore (as in my_value)
can be used.
Example :
my_variable21
21variable
g#roup
_group
name.age
_X

/*
/*
/*
/*
/*
/*

valid */
Invalid : first character can not be a number */
Invalid : special symbol (#) are not allowed */
valid */
invalid : special symbol (#) are not allowed */
valid */

Variable Declaration, Definition and Initialization in C

All variables should be declared in program before using it in any statement so that compiler
and runtime environment can determine memory depending on its type.
Syntax

datatype variable_name;

Example :

int x;
int y;
or int x,y;

stmt*/

/*int is datatype and x is the variable*/


/* First two declarations are combined in one single

float sum;
char name;

Note: A variable declaration does not allocate any memory for variable but variable definition
allocate required memory for that variable.
int x; Actually this is both declaration and definition so memory (4 bytes) is allocated for this
variable.
Assigning some value to a variable is called variable initialization. Equal sign(=) followed by
an constant expression is used for initialization.
Example : int x=10; /* Declaration, Definition and Initialization in
single stmt */
int y=20;
or int x=10,y=20;
float 10.5;
char name='A';

Lvalues and Rvalues in C


Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and can not appear on the left-hand side.
int x=100;
int y=x;
100=200;

/* Statement 1 : valid*/
/* Statement 2 : valid*/
/* Statement 3 : invalid */

In Statement 1, x is lvalue and 100 is rvalue.


In Statement 2, x is rvalue and y is rvalue.
In Statement 3, 100 is numerical literals i.e. rvalue, so it can not be on left side of assignment.

Now we can say


lvalue : An expression that is an lvalue may appear as either the left-hand or right-hand side
of an assignment(=).
rvalue : An expression that is an rvalue may appear on the right- but not left-hand side of an
assignment(=).

printf() and scanf() in C


printf() is an inbuilt library function used to display output on the console (screen).
General form:

printf(<format string(s)>, <list of variable(s)>)

Example:
Lets assume: name='A', age=21, sal=50000.0
printf("Hello!");
/*
printf("%c %d %f",name,age,sal);
/*
printf("name=%c age=%d salary=%f",name,age,sal);
/*
printf("name=%c\n age=%d\n salary=%f",name,age,sal);/*

Line
Line
Line
Line

1
2
3
4

*/
*/
*/
*/

Output:
-----------------------------------------Hello!
/* Line 1 output*/
A 21 50000.000000
/* Line 2 output*/
name=A age=21 salary
/* Line 3 output*/
name=A
/* Line 4 output*/
age=21
salary=50000.000000

Here %c,%d and %d etc. are called format specifiers in c


%c : for printing characters
%d : for printing integers
%f : for floating point
%s : for strings
%lf : for double

scanf() is an inbuilt library function used to accept input that users enter through the
keyboard.
General form:

scanf(<format string(s)>, & <list of variable(s)>)

Note the & symbol indicates address.


Example:
/*Addition of two numbers*/
#include<stdio.h>
int main()
{
int a, b, sum;

printf("please enter the value of a and b\n");


scanf("%d%d",&a,&b);
/* reading values from console in variables a and
b */
sum=a+b;
printf("a=%d, b=%d, sum=%d", a,b,sum);
}
Output:
---------------------------------please enter the value of a and b
23
45
a=23, b=45, sum=68

Syntax wise scanf() is almost similar to printf(), except for two main important differences :
1. Within the pair of double quotes there should occur only format specifiers like %c %d
%f etc.
2. The variable name must always be preceded by the 'address of' operator & .
Note: Header file to be included for printf() and scanf() function is : #include<stdioh.>

Arithmetic Operators in C
Operators used for arithmetic operations like addition, subtraction, multiplication division
etc. are called arithmetic operators.

Operator Description

Example Result

Adds both the operands

20 + 10

30

Subtracts second operand from first operand

20 - 10

10

Multiply both the operands

20 * 10

200

Second operand divides first operand

20 / 10

Modulus operator, gives the remainder after


division

20 % 10

Modulus operator (%) is used only with integer values,not for floating points numbers and
sign(+ or -) is always the sign of numerator.
Example:
3 % -2 = 1 [ Divide 3 by 2. The remainder is 1 and +ve sign from numerator]
-3 % 2 = -1 [ Divide 3 by 2. The remainder is 1 and -ve sign from numerator ]
3.0 % 1.5 = ? [invalid, modulus operator can not be used with floating point numbers]

Arithmetic Expressions in C
An expression consisting of arithmetic operators, constants and variables to perform
meaningful computation is called arithmetic expression.
For example
1.5+2-3*5

// 1, 2, 3, and 4 are operands and +, -* are arithmetic operator

2*(a+b)-4

In which order we perform the operation is very important and final result depends on it.
For Example : 8-4/2*3
If we perform the operation from left hand side :
8-4/2*3 = 4/2*3 = 2*3 = 6 //But 6 is not correct answer
Or.
If we perform operation from Right hand side :
8-4/2*3 = 8-4/6 = 8-0 = 8 // Even 8 is not correct answer
So the correct way is:
8-4/2*3 = 8-2*3 = 8-6 =2 // Using BODMAS rule, 2 is correct answer

BODMAS rule for arithmetic expression evaluation

Bracket will have the first precedence

Of operator will have the second precedence

Division operator will have the third precedence

Multiplication operator will have the fourth precedence

Addition operator will have the fifth precedence

Subtraction operator will have the sixth precedence

Assignment Operators in C

Assignment operator (=) is used to store or copy values into memory location. Copying or
storing into memory location is called assigning hence the name is assignment operator.
Syntax : variable = expression; // expression can be a
constant/variable/expression

For example :
x = y;

//Store the value of y into x*/

x = 4 + 5;

//Compute the addition of 4 and 5, .i.e 9 and store it into variable x

pi = 3.1416;

// Store 3.1416 into variable pi

There are many shorthand notations for assignment operators. Like a+=1, it is equivalent to a
= a + 1; Below table shows short hand assignment operator and their description.
Operator Example Meaning Description
+=

a += 2

a = a + 2 Perform a+2 and store result in a

-=

a -= 2

a = a - 2 Perform a-2 and store result in a

*=

a *= 2

a = a * 2 Perform a*2 and store result in a

/=

a /= 2

a = a / 2 Perform a/2 and store result in a

%=

a %= 2

a=a%
2

<<=

a <<= 2

a = a << Perform a<<2 and store result in


2
a

>>=

a >>= 2

a = a >> Perform a>>2 and store result in


2
a

&=

a &= 2

a = a & 2 Perform a&2 and store result in a

^=

a ^= 2

a=a^
2

|=

a |= 2

a = a | 2 Perform a|2 and store result in a

Perform a%2 and store result in a

Perform a^2 and store result in a

Increment and Decrement Operators in C


Increment (++) and decrement (--) are very powerful and compact operators in C. Both are
unary operator so have only one operand. Increment operator increment operand value by 1
and decrement operator decrement value by one.
Lets discuss each in detail.

Increment ( ++ ) operator in C
Increment operator (++) increments the value by 1.
For example
a++ or ++a

// this is equivalent to a = a + 1

Based on position of operator, it is classified into two type.


1. Post increment (a++)
2. Pre increment (++a)
If both increments the operand value by 1 then whats the difference between them? we will
discuss the difference after decrement operator because same concept applies to pre and post
decrement operator too.

Decrement ( -- ) operator in C
Decrement operator (--) decrements the value by 1.
For example
a-- or --a

// this is equivalent to a = a - 1

Based on position of operator, it is classified into two type.


1. Post decrement (a--)
2. Pre decrement (--a)

Difference between pre and post, increment decrement


operators
Post, as the name indicates , post increment or decrement means, increment or decrement
after (post) the operand value is used.
Lets understand it with an example
#include<stdio.h>
int main()
{
int i=1,j=1,k=0,l=0;
k=i++;
/* k=i, i=i+1 First copy i to k then increment i */
l=j--;
/* l=j, l=l-1
First copy j to l then decrement j */
printf("i=%d j=%d k=%d l=%d",i,j,k,l);
}
output

-------------------i=2 j=0 k=1 l=1

In above program you can see the values of k and l are still 1 but i is incremented by 1 and j
is decremented by 1. In k=i++, first values of i is used and then it is incremented because ++
operator is after i, .i.e post increment. same in case of l=j-- .
In case of Preincrement or decrement, operand value is first incremented or decremented then
is is used.
#include<stdio.h>
int main()
{
int i=1,j=1,k=0,l=0;
k=++i;
/* i=i+1, k=i, First increment i then copy i to k*/
l=--j;
/* l=l-1,l=j
First decrement j then copy j to l */
printf("i=%d j=%d k=%d l=%d",i,j,k,l);
}
Output
-------------------i=2 j=0 k=2 l=0

In above program ++ and -- is used as pre increment and decrement operator so in statement
k=++i; first i values is incremented by 1 and then it is copied to k. Same in l=--j;
Relational Operators in C

The relational operator is also called compare operators are used to compare two operands. The
two operands may be constants, variables or expressions. After comparing two operands it gives
the result in true (always 1) or false ( always 0).
The relational operator and the meaning associated with them are shown in below table.
Operat
Meaning
or

Description

Example

==

Equal

Checks if the value of two operands is equal or not, (5 == 7)


if yes then condition becomes true.
is false

!=

Not equal

Checks if the value of two operands is equal or not, (5 != 7)


if values are not equal then condition becomes true. is true.

>

Checks if the value of left operand is greater than


Greater Than the value of right operand, if yes then condition
becomes true.

(5 > 7) is
false

<

Less than

Checks if the value of left operand is less than the


value of right operand, if yes then condition
becomes true.

(5 < 7) is
true.

>=

Checks if the value of left operand is greater than or


Greater than
(5 >= 7)
equal to the value of right operand, if yes then
or equal
is false
condition becomes true.

Operat
Meaning
or
<=

Description

Example

Checks if the value of left operand is less than or


Less than or
equal to the value of right operand, if yes then
equal
condition becomes true.

(5 <= 7)
is true.

Logical Operators in C

Like logic gates AND, OR and NOT whose output is 1 or 0, we have logical operators in C.
After evaluation, expression consisting of logical operators results in either true or false and
hence such expression are called logical expression.
Below table shows the logical operators in C.
Operat
Description
or
!

It is called Logical Not (unary operator). Used to


negate the state of its operand. if operand is
true(1), Not makes it false(0).

Example
if x is TRUE then !
x is FALSE

if A=TRUE,
B=FALSE
&&

It is called logical AND operator. If both the operands


A && B is FALSE
are true then it AND of both is TRUE else AND of
both is false.
A && A is TRUE
B && B is FALSE

if A=TRUE,
B=FALSE
||

It is called logical OR operator. If any one operand is


A || B is TRUE
true then OR of both is TRUE, if both operands are
false then OR of both is false.
A || A is TRUE
B || B is FALSE

Conditional Operators in C
The conditional operator also known as ternary operator. It is called ternary operator because
it operates on 3 operands.
Syntax:
(exp1) ? exp2 : exp3 ;

where

exp1 is expression that evaluates to true or false.

if exp1 is true, exp2 is executed.

if exp1 is false, exp3 is executed.

Example:
int x=10; y=20;
int max = (x > Y) ? x : y;

In above example. first (x > y) is evaluated and result is false (as 10 > 20 is false). So exp3 is
executed (i.e. y ) and y value is copied to max.

Bitwise Operators in C
A bit is the basic unit of information in computing and digital communications. Data are
stored in memory in form of bits (0 or 1).The operator that are used to manipulate the bits are
called bit wise operators.

Bit-wise AND

Bit-wise OR

Bit-wise XOR

Left shift

<<

Right Shift

>>

Bit-wise Negate

&
|
^

Bit-wise AND "&" Operator


The bitwise AND operator is a single ampersand: & and remember it different from logical
AND (&&). This operator operates on bits of opearads. Both the operands should be of same
type (int, char etc.). Below table shows the operations of bit-wise AND operator
First Bit

Second Bit

First Bit & Second Bit

By looking at above truth table we can say that AND(&) of two bits is 1 only when both bits
are 1 else its 0. In first 3 rows AND of both bits are 0 because either both or at least one bit is
0. In last row both bits are 1 so the result is 1.
Example:
Lets assume, char a=1, b=3; So what will be a & b = ?
Solution:
Binary of a = 0 0 0 0 0 0 0 1
Binary of b = 0 0 0 0 0 1 0 1
-------------------------------a & b = 0 0 0 0 0 0 0 1
--------------------------------

Bit-wise OR "|" Operator


Bit-wise OR (|) works exactly almost same as bit-wise AND. The only difference is that any
one bit out of two should be 1 to get the result 1.
First Bit

Second Bit

First Bit | Second Bit

In above truth table only first row result is 0 because both the bits being OR'ed are 0.
For Example:
char a=1, b=3; So what will be a & b = ?
Solution:
Binary of a = 0 0 0 0 0 0 0 1
Binary of b = 0 0 0 0 0 1 0 1
-------------------------------a & b = 0 0 0 0 0 1 0 1
--------------------------------

Bit-wise XOR "^" Operator


XOR operator is represented by ^ and is also called an Exclusive OR operator. It results in 0
if both the bits are same ( both 0 or both 1).

First Bit

Second Bit

First Bit | Second Bit

In above table, first and last row have both bits same that why result is 0.
For Example:
char a=1, b=3; So what will be a & b = ?
Solution:
Binary of a = 0 0 0 0 0 0 0 1
Binary of b = 0 0 0 0 0 1 0 1
-------------------------------a & b = 0 0 0 0 0 1 0 0
--------------------------------

Left shift "<<" Operator


The left shift operator is represented by <<. It shifts each bit of operand to left by the number
of bits specified.
Syntax: integer_constant_variable << number_of_bits_to_be_shifted ;
Example: x << 1 ;
Lets assume x=65, So x<<1 will shift each bit of x (0100 0001) by 1 bit to left and right most
bit is filled with zero. See below diagram

Right Shift ">>" Operator


The right shift operator is represented by >>. It shifts each bit of operand to right by the
number of bits specified.

Syntax: integer_constant_variable >> number_of_bits_to_be_shifted ;


Example: x >> 1 ;
Lets assume x=65, So x>>1 will shift each bit of x (0100 0001) by 1 bit to right and left most
bit is filled with zero or one.if left most bit is 0 then filled with 0, if left most bit is 1 then
filled with 1. See below diagram

Bit-wise Negate "~" Operator


It is also called one's complement of a number. On taking one's complement of a number, all
1's present in the number are changed to 0's and all 0's are changed to 1's.
For example :
1's complement of 0011 0111 is 1100 1000.
Special: comma, sizeof Operators in C

Lets discuss few special operator supported in C. This includes comma operator, sizeof
operator, pointer operators (& and *) and member selection operators (. and ->). Pointer
operators will be covered while discussing pointer and member selection operators will be
covered with structure and unions.
Comma Operator in C

Comma operator represented by comma ( , ) accepts two operands. It is used to combined two
or more statement into single statement. We can write compact statement using this operator.
The statements separated by comma operator are executed one by one from left to right. it has
least precedence during expression evaluation.
Example:
int x=1;
int y=x+1;
int z=x+y;

Above three statements can be combined using comma operator

int x=1, y=x+1, z=x+y; /* It will be evaluated from left to right */

Now what will the output of below program?


#include<stdio.h>
void main( )
{
int x,y,z;
z = (x=10, y=30, x+y);
printf( "z=%d", z ) ;
}

If your answer was 40 then you are correct. lets see how it has been calculated. First 10 is
copied to x, then 20 is copied to y and after that x+y is calculated and finally result is stored
in z.
sizeof() Operator

sizeof() operator returns number of bytes occupied by variable or constant in the


memory. The size of operator works on variables, constants and even on data types
sizeof(operand);
For Example:
sizeof(char)

1 byte

sizeof(int)

4 bytes

Don't be surprised if you get other result for above example because size of datatype is
machine dependent.

Decision Control in C
We have seen the common decision control structures in C
1. If Else control
2. Nested If
3. If Else If Ladder
Lets discuss each of these in detail with some real world Examples!

If Else Control Statement in C


Syntax:
if(condition)
{
----;
statements set1; // Compound statements
----;
}
else
{
----;
statements set2;
----;
}

If the condition Evaluates to True then set1 statements are EXECUTED and set2 are
NOT executed.

if the condition is False then statements set1 are NOT executed and set2 inside the
else block are EXECUTED.

Single Statement:
If there is only one statement inside the if or else block the braces "{ }" can be removed.
Syntax:
if (condition)
statement;
else:
statement2;

Note 1: Zero is False and any non zero value is treated as True in C.
Note 2: Multiple Statements are technically called Compound Statements.
Example of If in C:
#include<stdio.h>
int main()
{
int var1=0;
if (var1 < 10)
{
printf("Inside If Condition\n");
printf("2nd statement inside If Condition\n");
}
else
{
printf("Inside Else Condition\n");
printf("2nd statement inside Else Condition\n");
}

For Single Statement the If block could be written as:


if (var1 < 10)
printf("Inside If Condition\n");
else
printf("Inside Else Condition\n");

Be careful with these single statements:


int var1=10;
if (var1 != 10)
printf("Statement1");
printf("Statement2 Not under if block");

Here only "statement1" is under if block, the Statement2 is not under if block and is executed
irrespective of the result of the condition var1!=10.

Nested If in C
A nested if means placing one or more if statements inside another if statement.
Syntax of Nested If in C
if(condition1)
{
//statementset1
if(condition2)
{
//statementset2
}
else // executed if condition3 is false
{
//statementset3
}
}
else
// executed if condition1 is false
{
// statementset4
}

If Condition1 is true, execute statementset1 and then check if condition2 is true, if yes
execute statementset2 also, else execute statementset3.
If Condition1 is false execute statementset4.
Example of Nested If in C
int i=10,j=20;
if(i==10)
{
if(j==20)
{

printf("i=10 and y=20");

i=10 and y=20 is printed only if both the if condition evaluates to true.

if-else-if Ladder in C
This decision control structure is used when you have multiple conditions and you have to
execute the corresponding statements based on which condition is true.
Syntax:
if(boolean_expression1)
{
//... StatementSet1
}
else if (boolean_expression2)
{
// StatementSet2
}
else if (boolean_expression3)
{
// StatementSet3
}
// any number of else if
else
{
//Last StatementSet
}

Example:
int a =10;
if( a>10)
printf("a>10");
else if( a>20)
printf("a>20");
else if(a<10)
printf("a<10");
else
printf("No condition matched!");

Real world Example:


Lets say you are alone at your home and you feel hungry, you go to the kitchen to see if there
is anything available to eat.
Here is the thought process:
if( there is bread and butter)
{
spread the butter on bread

eat the bread


}
else if ( there is oats and milk)
{
eat oats and milk
}
else if ( there is maggie )
make maggie and eat it

The conditions are written in the preference order and if any condition matches the rest
of the ladder is skipped!
If you find bread and butter, your search just ends! you do not go and search for oats or
maggie after that.
For Loop in C

The for loop in C allows us to execute a set of statements a specific number of times.
Syntax of for loop in C:
for(initialization;condition;iteration)
{
//body
}

If there is just one statement in the body , the braces are not required.

Control Flow of for loop in C:


1. The initialization statement is executed first.It initializes the value of the
"loop control variable" which acts as the counter of the for loop. It
executes only once at the beginning of the for loop.

2. The condition statement is executed next and tests the value of the loop
control variable and decides whether the body of the for loop can be
executed. It can only be a boolean expression. If the condition evaluates to
true , the body is executed otherwise the loop terminates and the
statement after the for loop is executed.
3. The body of the for loop is executed next.
4. Once the control finishes executing the last statement of the body, the
control goes to the iteration statement. It updates/modifies the value of
the loop control variable/ counter and prepares for the next iteration.
5. Then the control again enters the condition statement and checks whether
the updated control variable still satisfies the condition.

Thus, the steps 2, 3 and 4 are executed in a loop until the condition evaluates to false.
Example of for loop in C:
#include<stdio.h>
int main()
{
int i;
for(i=5;i<10;i++)
{
printf("i=%d",i);
}
printf("After for loop");
}

Output:
i=5
i=6
i=7
i=8
i=9
After for loop

Explanation:

Notice that the variable i is declared inside the initialization statement of


the for loop. This means that the scope of "i" is only inside the for loop.

First, i is initialized to 5. Then i<10 condition is tested and since it is true,


the control enters the body.

The statement println is executed and i=5 is printed.

Then, the iteration statement (i++) is executed and increments the value
of i to 6.

This updated value of i is tested again in the condition statement (i<10) ,


since 6<10 is true, the control again enter the body and prints i=6.

This goes on, till i=9 is printed.

When the control enters the iteration statement this time, i becomes 10.

The condition is tested and i<10 becomes false.

The control comes out of the for loop and "After for loop" is printed!

Try to go through the above explanation once more to grasp the whole
concept thoroughly. This is one of the most important concept and many
interview questions are asked from for loop based on the control flow.

Variations of for loop in C

The initialization statement, condition statement and iteration statement are not compulsory,
and they can be kept empty.
We can rewrite the above program in these way also:
Variation 1: Without the initialization and iteration statement
#include<stdio.h>
int main()
{
int i=5;
for(;i<10;)
{
printf("i=%d",i);
i++;
}
printf("After for loop");

In the above program, we have intentionally kept the initialization and iteration part empty.
But, T achieve this, we had to write the initialization statement before the for loop and had to
increment the counter inside the body of the loop.
Variation 2: Without the Condition Statement

In the following program, we have eliminated the condition statement also, but we have to
modify the body of the for loop so that the it does not become an infinite loop. This is done
by using the break statement inside the for loop body. when the value of i becomes 10 , the
break statement terminates the for loop. We will discuss the break statement in the next topic.
#include<stdio.h>
int main()
{
int i=5;
for(;;)
{
printf("i=%d",i);
i++;
if(i==10)
break;
}
printf("After for loop");
}

Variation 3: Infinite loop in C using for

The following program is an infinite loop as all the three parts of the for loop are kept empty.
#include<stdio.h>
int main()
{
for(;;)
{
printf("inside Infinite Loop");
}
}

While and Do-While loop in C


There are 2 variations of while loop in C
1. while loop
2. do while loop

While Loop in C

The while loop is the most fundamental loop statement in C and continuously executes a set
of statements while the condition is true.
Syntax of while loop in C:
while(condition)
{
//statements
}

Example of while loop on C:


int i=5;
while(i<10)
{
printf("i=%d",i);
i++;
}

Output:
i=5
i=6
i=7
i=8
i=9
Here, 1st the condition(i<15) is checked, if it is true then the statements inside the while loop
body are executed, after the last statement is executed, the control again goes to the
condition. The control enters the body of while loop only when the condition is still true.
Note: i++ is very important here, without it the while loop becomes an infinite loop.

A Real World Example of while loop in C:


while(are there cookies in the jar?)
{
eat one cookie;
}
close the cookies jar.

Consider that your Mom has gone out, and asked you not to eat the cookies kept in the
kitchen. But they are your favorite cookies and obviously, you are gonna eat them up!
1. You open the cookie jar
2. Check if there are cookies in it.
If no, close the jar and run away!(Condition)

3. Take one cookie and eat it, which decreases


the number of cookies in the jar by 1.
4. Check again if there are more cookies in the jar . (i.e. repeat step 2)
5. Take another cookie and eat it which again decreases
the number of cookies in the jar by 1.
6. Check again if there are more cookies in the jar . (i.e. repeat step 2)
7. Take another cookie and eat it which again decreases the
number of cookies in the jar by 1.

Notice that the steps 4 and 6 are same as step 2, and steps 5 and 7 are same as step 3.
The above example can be re-written as:
1. You open the cookie jar
2. Check if there are cookies in it. if No go to step5 (Condition)
3. Take one cookie and eat it, which decreases the number of cookies in the
jar by 1.
4. Go to step 2
5. Close the jar and run away!

do while loop in C

do while loop is almost same as while loop except one difference:


The do while loop executes the statements in the body of the loop at least once!
In the previous cookies example, Lets say that you already know that there is atleast one
cookie in the jar, so you need not check for the first time if there is cookie in the jar, you just
know it!

Real World Example of do while loop in C:


1. You open the cookie jar
2. Take one cookie and eat it, which decreases the number of cookies in the
jar by 1.
3. Check if there are more cookies in it.
if Yes go to step2 else go to step4 (Condition)
4. Close the jar and run away!

Syntax of do-while loop in C:


do
{
//statements
}
while(condition)

As the condition is at the end, the statements are executed at least once anyways, then the
condition is tested, if it is true, the statements are executed again else the loop terminates.

Example of do while loop in cpp


int i=5;
do
{
printf("i=%d",i);
i++;
}
while(i<10)

Output:
i=5
i=6
i=7
i=8
i=9

Difference between while loop and do-while Loop in C


Consider the following program:
i=10;
while(i<10)
{

printf("i=%d",i);

i++;

}
printf("End of while loop,i=%d",i);

Output:
End of while loop,i=10
Do While version
do
{
printf("i=%d",i);
i++;
}while(i<10)
printf("End of do while loop, i=%d",i);

Output:
i=10
End of do while loop,i=11

Notice that the body of while loop did not execute even once, hence the value of i was not
incremented,but in do-while loop, the body was executed for the first time and i was
incremented to 11, and then the condition was tested.

switch case in C
Switch statement is an alternative to if-else ladder in C. It provides us a simple and organized
way to execute statements based on a condition.
When the condition increases, the if-else ladder becomes clumsy and untidy,switch control
solves this using cases.
Syntax of switch in C:
switch(expression)
{
case value1: //statements
break;
case value2: //statements
break;
}

Some Important points to remember :


1. When a case matches, the corresponding statements get executed until a break is
encountered or the end of switch block is reached.

2. There can be as many cases as you want inside switch block.


3. The expression can be only integer or char
4. The value in case should be same as the expression in switch.
5. The default case is optional
6. The default case handles all the cases that are not present i.e. if none of the cases
match default case is executed!
7. break statement is very important as without it switch fall-through will happen i.e. All
the cases after the matching case are executed in sequence until a break is found or the
end of switch block is encountered.
8. The last break is not necessary as the switch block ends anyways.
9. The default case should always be placed at the end , as any case placed after it can be
never executed.
Note:
1. if-else can test different type of conditions but switch statement can only test
expressions based on a single integer, enumerated value.
2. Switch is also more efficient than if-else because the compiler creates a jump
table for each case under switch. Moreover, since switch only tests for
equality and knows the data type of the variable, it runs much faster for a large
number of cases.
Example of switch in C:
#include<stdio.h>
void main()
{
int i=10;
switch(i)
{
case 10 : printf("Case 10!");
break;
case 20 : printf("Case 20!");
break;
default : printf("Default Case");
break;
}
}

Output:
Case 10!

The value of is 10 which matches the first case value and hence the statements in case 10 are
executed. "Case 10!" is printed and then break takes the control out of the switch block and
the program ends.

Nested Switch in C
When we place another switch inside the statements of an outer switch it is called Nested
Switch.
Syntax of Nested Switch in C:
switch (variable1)
{
case value1: //...statements
break;
case value2:
switch(variable2)
{
case value1: //... statements
break;
case value2: //statements
break;
default: // statments
break;
}
break;
default : //statements
break;
}

Points to remember:
1. The value1 inside the outer and inner switch are different and do not conflict.
2. The inner switch is executed only when the value of variable1 is equal to value2. Even if
the value of variable2 in equal to inner value1 or inner value2, it will not get executed until
the value of variable1 == value2
3. The inner break only exits the inner switch.
Example of Nested Switch in C:
#include<stdio.h>
void main()
{
int i=20,j=30;
switch(i)
{
case 10 : printf("i == 10");
break;
case 20 :
switch(j)
{
case 20: printf("i==20 and j==20");

break;
case 30: printf("i==20 and j==30");
break;
default: printf("Inner Default Case");
break;

}
break;
default : printf("Outer Default Case");
break;

Output:
i==20 and j==30

1. What is difference between object oriented and procedure oriented programming?

A:

Procedure oriented language is based on function while object oriented is based on real
world entity.

Lets Discuss
2. What is the difference between char *a and char a[]?
A:
char a[] = "string";
char *a = "string";
The declaration char a[] asks for space for 7 characters and see that its known by the name
"a". In contrast, the declaration char *a, asks for a place that holds a pointer, to be known
by the name "a". This pointer "a" can point anywhere. In this case its pointing to an
anonymous array of 7 characters, which does have any name in particular. Its just present
in memory with a pointer keeping track of its location.

char a[] = "string";


+----+----+----+----+----+----+------+
a: | s | t | r | i | n | g | '\0' |
+----+----+----+----+----+----+------+
a[0] a[1] a[2] a[3] a[4] a[5] a[6]

char *a = "string";
+-----+

+---+---+---+---+---+---+------+

| a: | *======> | s | t | r | i | n | g | '\0' |
+-----+

+---+---+---+---+---+---+------+

Pointer Anonymous array It is crucial to know that a[3] generates different code
depending on whether a is an array or a pointer. When the compiler sees the expression
a[3] and if a is an array, it starts at the location "a", goes three elements past it, and returns
the character there. When it sees the expression a[3] and if a is a pointer, it starts at the
location "a", gets the pointer value there, adds 3 to the pointer value, and gets the character
pointed to by that value.
If a is an array, a[3] is three places past a. If a is a pointer, then a[3] is three places past the
memory location pointed to by a. In the example above, both a[3] and a[3] return the same
character, but the way they do it is different.
Doing something like this would be illegal.
char *p = "hello, world!";
p[0] = 'H';
Lets Discuss
3. What's the difference between const char *p, char * const p and const char * const p?
A:
const char *p - This is a pointer to a constant char. One cannot change the value
pointed at by p, but can change the pointer p itself.

*p = 'A' is illegal.
p = "Hello" is legal.

Note that even char const *p is the same!

const * char p - This is a constant pointer to (non-const) char. One cannot change the
pointer p, but can change the value pointed at by p.

*p = 'A' is legal.
p = "Hello" is illegal.

const char * const p - This is a constant pointer to constant char! One cannot change the
value pointed to by p nor the pointer.

*p = 'A' is illegal.
p = "Hello" is also illegal.
Lets Discuss
4.
None
A:
None
Lets Discuss
4.
None
A:
None
Lets Discuss
6.
Null
A:
Null
Lets Discuss
7. What is Selenium ?
A:
Selenium is an open source automation testing tool.

Used only for web based applications.


Supports writing of testcases in different languages like Html, C#, Java, Phython, Ruby
etc.
Supports the execution of test cases on multiple web browsers such as Firefox, Chrome,
IE, Opera, HtmlUnit, Android, iOS .
Mainly used for functional, regression and load testing.
Released under Apache 2.0 licence.
It can be downloaded from seleniumhq.org.
Highly flexible as it provides many options for locating UI element and comparing
expected test results against actual application behaviour. It can be deployed on Windows,
Linux, and Macintosh.

What is the output of:

#include<stdio.h>
int main()
{
int x=40;
{
int x=20;
printf("%d",x);
}
printf("%d",x);
return 0;
}

A.

40 40

B.

20 40

C.

40 20

D.

Compilation Error

See Answer & Explanation Lets Discuss


Correct answer is : B
Explanation

The variable declared inside the inner block replaces the x declared in the outer block, hence
it prints 20 at 1st printf.
When the inner block ends, the scope of inner x also ends and hence the value of x becomes
40 in the outer block.
What is the output of the following program:

void main( )
{
int i = 2, j
float a, b ;
k = i / j *
l = j / i *
a = i / j *
b = j / i *
printf( "%d
}

= 3, k, l ;
j ;
i ;
j ;
i ;
%d %f %f", k, l, a, b ) ;

A.

3322

B.

3 3 0 2.000000

C.

3 2 0.000000 3.000000

D.

0 2 0.000000 2.000000

See Answer & Explanation Lets Discuss


Correct answer is : D
Explanation
RHS is evaluated first and then the value is promoted to float, float arithmetic is not used here
as there is no variable on the RHS that is float.
The Float is printed with decimal followed by 6 zeros.
What is the output of:
main( )

3 {

int a,
a = -3
b = -3
printf
}

A.

b
(

;
- 3 ;
- ( - 3 ) ;
"a = %d b = %d", a, b ) ;

-3 3

B.

-6 0

C.

0 -6

D.

None of the Above

See Answer & Explanation Lets Discuss


Correct answer is : C
Explanation
-3 - -3= -3 + 3 = 0
-3 --(-3)= -3 - 3 = -6
4 C language was developed by?
A.

Dennis Richie

B.

Martin Richards

C.

Bill Gates

D.

Ken Thompson

See Answer & Explanation Lets Discuss


Correct answer is : A
Explanation
No Explanation needed !!!
5 A character variable can store x characters at a time:
A.

1 character

B.

8 character

C.

256 character

D.

None of the above

See Answer & Explanation Lets Discuss


Correct answer is : A
Explanation
A character variable is of 1 byte length and can store just 1 character at a time

You might also like