0% found this document useful (0 votes)
0 views24 pages

Notes CCP U2

The document provides an overview of data types, variables, constants, and expressions in the C programming language. It explains the differences between constants and variables, outlines the fundamental data types along with their storage sizes and value ranges, and details the rules for naming variables. Additionally, it covers operators, expressions, and logical data representation in C.

Uploaded by

thepsyforge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views24 pages

Notes CCP U2

The document provides an overview of data types, variables, constants, and expressions in the C programming language. It explains the differences between constants and variables, outlines the fundamental data types along with their storage sizes and value ranges, and details the rules for naming variables. Additionally, it covers operators, expressions, and logical data representation in C.

Uploaded by

thepsyforge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

KIET, GZBD

UNIT # 2 Data – Types


Variables, Constants & Expressions
The alphabets, nos. & special symbols when properly combined create constants, variables & keywords.
 A constant(const) is an entity that doesn’t change. Value that never changes within a program is
stored in constant & named once. All values are constants, as:3, 5.6, ’A’, ”hello”
 A variable is an entity that may change, also called as identifier. Value that may change on the basis
of various calculations is stored within a variable name in memory.

C constants

Primary constants Secondary constants

Integer constant Array


Real constant Pointer
Character constant Structure
Union
Integer constants:- (Rules/properties) Enumeration
(a) It must have at least one digit
(b) not have decimal point
(c) can be +ve or -ve, but by default(if not defined) +ve
(d) No commas/blanks are allowed within integer constant.
(e) Range  -32768 to 32767 (for 16-bit compiler) and occupies 2 Bytes space.
(f) Integer constant:023=>23 in octal no.sys;0x23=> 23 in hex no.sys;23L or 23l=>long int,
23U or 23u=>unsigned int
Real Constants :- (also called as Floating point Const.)
Can be written as –: fractional form Or exponential form
(a) It must have atleast one digit.
(b) Decimal point present.
(c) +ve or –ve, default +ve
(d) No comma/blank allowed.
(e) It is represented in exponential form if the value is either too small or too large.
In exponential form two parts of constant 
Mantissa exponent
e
Range : is 1.2E-38 to 3.4E+38 and takes 4 bytes.eg: +3.2 e-5 or 4.1 e8
1
Anurag Tewari
KIET, GZBD

Character Const:-
Single – alphabet/digit/special symbol kept within single inverted commas.
e.g. ‘A’, ’I’, ’5’, ’=’
Range is -128 to 127, occupies 1 Byte of memory space.
Escape sequences: An escape sequence is a sequence of characters that does not represent itself
when used inside a character or string literal, but is translated into another character or a sequence of
characters that may be difficult or impossible to represent directly. Only, its effect is shown in result.

Types of C VARIABLES (Identifiers):-


Any memory Location can be represented by any variable or identifier name which can
keep any type of data (integer/float/character) in it. Data is constant (for some calculation)
Rules for Designing Variable Names:
 First character must be alphabet or underscore.
 Must have only alphabet, character, digits or underscore.
 First 63 characters Of an identifier (var.) are significant
 Cannot duplicate a keyword.
 It may not have a space or a hyphen.(ex: int a 1, int a-1)
Examples:
&sum  illegal a  legal
2name  illegal st_name legal
Sum-salary  illegal _asystem legal
& tdnt number  illegal _Bool legal
int  illegal INT_MIN (system defined)  legal

2
Anurag Tewari
KIET, GZBD

Data Types in C

Fundamental Data-Types Description:

Data-Type Storage Value range Format-Specifier


size

char 1 byte -128 to 127 %c

unsigned char 1 byte 0 to 255 %c

signed char 1 byte -128 to 127 %c

-32,768(215) to 32,767(215-1 ) %d
or
int 2 or 4 bytes
-2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295 %u or %i

Short 2 bytes -32,768 to 32,767 %hi or %hd

3
Anurag Tewari
KIET, GZBD

unsigned 2 bytes 0 to 65,535 %hu


short

Long 8 bytes -9223372036854775808 to %l or %ld or %li


9223372036854775807

unsigned long 8 bytes 0 to 18446744073709551615 %lu

Float 4 byte 1.2E-38 to 3.4E+38 %f or %g or %e

(6 decimal places)

Double 8 byte 2.3E-308 to 1.7E+308 %lf or %lg or %le

(15 decimal places)

long double 10 byte 3.4E-4932 to 1.1E+4932 %Lf or %Lg or %Le

(19 decimal places)

Others are as:


String type- %s Pointer type - %p
Unsigned Integer in octal number system - %o or %O Unsigned Integer in hexadecimal number system -
%x or %X
sizeof() can be used to get the size (no. of bytes) of any Data-Type as:
Type-Modifiers:
It changes the base-type to get a new type=> range & Arithmetic props are modified.
Corresponding keywords available in C are:
1. signed
2. unsigned
3. short
4. long
Type-Qualifiers: They are used to indicate special properties of data within an object (variable).
Two qualifiers are defined:
1. Constant (const int i=10;)
2. Volatile: The volatile keyword is intended to prevent the compiler from applying any
optimizations on objects that can change in ways that cannot be determined by the compiler.
If we do not use volatile qualifier, the following problems may arise
1) Code may not work as expected when optimization is turned on.
2) Code may not work as expected when interrupts are enabled and used.
Data Object, L-value and R-value:
variables/Identifiers are used as data object which contain data in them.
LHS of ‘=’ is called L-value (generally name of identifier/variable)
RHS of ‘=’ is called R-value (generally value of identifier/variable or an expression which results
a value)
Eg. A= b*c+d; {b=4, c=3, d=-4}.
4
Anurag Tewari
KIET, GZBD

Operations on Variables:
Variables are Declared – name is given
Defined – memory space is reserved for above name
Initialized – used (computed) with 1st value Used–
Modified, Saved and printed…
data-type char codeidentifier (name)
code = ‘A’  initialization
int C = 0  initialization
When a variable is defined, it is not initialized (automatically). We must initialize any variable
with prescribed data before the function starts using it with some value otherwise a garbage value
may exist .
Operand: it is an entity on which an operation is to be performed. It can be : a var, const,
function call or a macro name. Eg. In expression:a+b, a & b are operands.
Operator: It specifies an operation to be performed on its
operands. Eg. In expression:a+b, ‘+’ is an addition operator applied on operands :a & b.

Expression: It is made up of one or more operands and operators in it. as: a=b+c
Primary expression – It consists of only one operand with no operator.
eg.
Name, literal constant, parenthetical expression
a, b12, 5,123.98,
price, ‘A’, “welcome”
INT_MAX

(2 * 3+4), (a = 23 + b * 6)
Simple expression: a+b has 1 operator: ‘+’
Compound expression: c=a+b has 2 or more operators: ‘+’ & ‘=’
Assignment expression(use of assignment operator:‘=’):
It evaluates the operand on the right side of the operator (=) & keeps its value in the variable on
the left.
2 types of assignment expressions.

Simple Assignment Compound Assignment


a = 5, x * = y +3 ≡ {x = x*(y+3)},
b = x +1,
i = i+1 x - = 4 ≡ {x = x-4}

5
Anurag Tewari
KIET, GZBD

Classification of operators=>

UNARY
OPERATOR
BINARY
BASED ON OPERATOR
NO. OF ARITHMETIC
TERNARY
OPERANDS OPERATORS
OPERATOR
RELATIONAL
OPERATORS
CLASSIFICATION
OF OPERATORS LOGICAL
OPERATORS

BASED ON BITWISE
ROLE OF OPERATORS
OPERATOR
ASSIGNMENT
OPERATORS

MISCELLANEOUS
OPERATORS

Types of operators,(based on no. of operands used):


1. Unary operators
It operates on one operand (operand on left or on right of operator),
as: in expression “-3”, ‘-’ is a unary minus operator It operates on 3 only.
Other unary operators are : ++(increment operator), --(decrement operator), &(address of operator),
sizeof( ) operator,!(logical not operator), ~(bitwise not operator) etc.
Expression types on the basis of position of ++ and --(Unary operators):
PostFix & PreFix expression : ++, - -
1. prefix: operator , operand, ex: ++ a(increment a by 1=>(a= a+1))
2. Post fix: operand, operator Variable, ex: a++(increment a by 1=>(a= a+1))
Evaluation of postfix ++: (first use then increment)
a++
x=a
x=a++ step(1) value of expression is a(assigned to x)

a = a +1
step(2) value of a is incremented by 1(assigned to a)
6
Anurag Tewari
KIET, GZBD

Evaluation of prefix: (first increment then use)

++ a a = a +1
(1) value of a is incremented by 1(assigned to a)
x=a++
x=++a
x=a
(2) value of expression is a after increment(assigned to x).
Similarly for a-- & --a
Both are: a= a – 1, after execution.

Examples to use above property: Difference between x++ and ++y


main()
{
int a,b,x=10,y=10;
a = x++;
b = ++y;
printf("Value of a : %d%d",a,x++);
printf("\nValue of b : %d%d",b,++y);
}
O/P:

#include <stdio.h>
main(){
int c=2,d=2;
printf("%d\n",c--); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed. }
Size of () :
It tells us the size, in bytes of a type or a primary expression.
Eg.
sizeof (int); => 2, size of integer data type is 2 bytes or 4 bytes.
sizeof(-345.23); => 4, size of floating point data type is 4 bytes
sizeof (x)

2. Binary operators
It operates on two operands (one operand on left and other on right of operator),
It is left to right associative
as: in expression “10+4”, ‘+’ operates on 10 and 4.
Other binary operators are: +, -, /, %, <<(left shift operator),==(equality operator),
&&(logical and operator) etc.

3. Ternary Operator (conditional operator)


It operates on three operands. As: conditional operator(? : ) is ternary operator.
Ex:
#include <stdio.h>
main(){
int d1,d2, larger;
printf("Enter two numbers a & b: ");
7
Anurag Tewari
KIET, GZBD

scanf("%d%d",&d1,&d2);
larger=d1>d2?d1:d2;
printf("Larger Number is = %d",larger);
}

• The conditional operator operator (?:) is just like an if .. else statement


that can be written within expressions.
• The syntax of the conditional operator is
exp1 ? exp2 : exp3
Here, exp means expression. Here exp1 is evaluated first. If it is true then exp2 is evaluated and becomes
the result of the expression, otherwise exp3 is evaluated and becomes the
result of the expression. For example,
large = ( a > b) ? a : b;
• Conditional operators make the program code more compact, more readable, and safer
to use as it is easier both to check and guarantee that the arguments that are used for
evaluation.
• Conditional operator is also known as ternary operator as it is neither a unary nor a binary operator; it
takes three operands.
Example:
main() { main()
int a=2,b=3,c; {
c = ( a > b) ? a : b; int a=2,b=23,c=1, biggest ;
printf("%d",c); biggest = a > b ? ((a > c ? a : c) : (b > c ? b : c)) ;
} printf("\nThe biggest number is : %d", biggest) ;
}
O/P: 3 Output: 23

 Any statement written as a comment will never be executed by complier.


 No nesting is possible in comments.
/*- - -- --- -
/*- - -- --- -
- - - - -- */ invalid
- - - - - --
- - - - -- */

8
Anurag Tewari
KIET, GZBD

Arithmetical Operators: addition(+),subtraction(-),Multiplication(*),division(/),modulus(%) etc.


Modulus operator (%) :
It returns the remainder as a result after division operation
4 %3 = 1, -5 % 2 = -1
7% 3 = 1, 5 % -2 = 1, 2 % 3 = 2

Selection - Making Decision


Logical data :- A piece of data is called logical if it conveys the idea of true or false.
C has no logical data type. Integer can be used to represent logical data.
If a data Value is zero(‘0’)  false
If a data Value is non-zero (+ve or -ve) true
C99 std. has given Boolean data type. –: bool
- unsigned integer is in stdbool.h, bool, true, false are also defined in header files.

Logical operators:- 3 logical operators are defined in C-


‘Logical not’(!), ‘Logical and’(&&), ‘Logical or’(||).
 They are used for combining logical values & designing new logical values.
‘not’ operator (!) :
o It is a unary operator
to to
.It changes a true value   false and a false value   true
‘and’ operator (&&):
o It is a binary operator
o 4 combinations are possible in its operands.
o Result is  true only if both operands  true. otherwise always  false.
‘or’ operator ( | | ):
o It is a binary operator
o 4 combinations are possible in its operands.
o The result is false if both operands  false, Otherwise always  true.
Logical operators can be shown in a Table called as – truth- table:
not and or
x !x x y x&&y x y x || y
f t f f f f f f
t f f t f f t t
t f f t f t
t t t t t t
t: true and f:false.
Expressions connected by && or || are evaluated left to right and the evaluation stops as soon as truthfulness
or falsehood of the result is known. Thus, in an expression:
a. E1&&E2, where E1 and E2 are sub-expressions, E1 is evaluated first. If E1 evaluates to 0 (i.e. false),
E2 will not be evaluated and the result of overall expression will be 0 (i.e. false). If E1 evaluates to a
non-zero value (i.e. true) then E2 will be evaluated to determine the value of overall expression.

9
Anurag Tewari
KIET, GZBD

b. E1||E2, where E1 and E2 are sub-expressions, E1 is evaluated first. If E1 evaluates to a non-zero


value (i.e. true), E2 will not be evaluated and the result of overall expression will be 1 (i.e. true). If E1
evaluates to 0 (i.e. false) then E2 will be evaluated to determine the truth value of overall expression.
Example:
void main() main()
{
{
int a=10,b=-5;
int x=3,y=0; int i=0,j=0,k=2,l;
int c,d,u,v; l=i||j&&k;
c=a&&b;
d=a||b;
u=x&&y; printf("%d%d%d%d",i,j,k,l);
v=x||y; }
printf("%d%d%d%d",c,d,u,v);
} O/P-> 1 1 0 1

O/P-> 1 1 0 1 O/P:0 0 2 0
Examples:
main() { int i=1,j=1,k=2,l;
l=i||j++&&++k;
printf("%d %d %d %d",i,j,k,l); }
//O/P:1 1 2 1

main()
{ int i=0,j=1,k=2,l;
l=++i&&j++||++k;
printf("%d %d %d %d",i,j,k,l); }
//O/P:1 2 2 1

main()
{ int i=0,j=1,k=2,l;
l=++i&&--j||++k;
printf("%d %d %d %d",i,j,k,l); }
//O/P:1 0 3 1

main()
{ int i=0,j=1,k=2,l;
l=++i&&j--||++k;
printf("%d%d%d%d",i,j,k,l); }
O/p:1 0 2 1

Comparative Operators: ‘6’ comparative operators are provided by C.


we can keep them in to two groups – relational operator & Equality operator.

10
Anurag Tewari
KIET, GZBD

RELATIONAL OPERATORS
• Relational operators are used to compare two quantities (i.e. their
operands). There are six relational operators in C:

S.No Operator Name of Category ary of Precedence Associativity


Operator Operators amongst
relational
class

1. < Less than Relational Binary Level-I L→R


> Greater than operators
<= Less than or
equal to
>= Greater than or
equal to
2. == Equal to Equality Binary Level-II L→R
!= Not equal to operators

KEY POINTS:RELATIONAL
OPERATORS
 There should be no white space character between two symbols of
a relational operator.
 The result of evaluation of a relational expression (i.e. involving
relational operator) is a boolean constant i.e. 0 or 1.
 Each of the relational operators yields 1 if the specified relation is
true and 0 if it is false. The result has type int.
 The expression a<b<c is valid and is not interpreted as in ordinary
mathematics. Since, less than operator (i.e. <) is left-to-right
associative, the expression is interpreted as (a<b)<c. This means
that “if a is less than b, compare 1 with c, otherwise, compare 0
with c”.
 An expression that involves a relational operator forms a condition.
For example, a<b is a condition.

Ex:
main() main()
{ {
int a=2,b=3,c=1,d; int a=2,b=3,c=1,d;
d=a<b; d=a<b>c; //it is:(a<b)>c
printf("%d",d); printf("%d",d);
} }

Output: 1 Output: 0

Relational operator complements


> C omplement  of
  <=
Complement  of
<    >=

11
Anurag Tewari
KIET, GZBD

== C
omplement  of
  !=
We can also simplify operators as:
!(x >y)  x<=y
! (x < y)  x>=y
!(x! = y)  x==y
Programs objectives to utilize Relational & Logical Operators:
1. Wap to check whether i/p no. is even or odd.
2. Wap to check if the person is eligible for voting or not.
3. Wap to check if the i/p year is Leap year or not
4. Wap to calculate the salary of a person after increment, given conditions are- if experience is
between 0 to 3 years then 10% increment otherwise 20% increment will be given.

Precedence and associativity Of Operators


 The order in which the operators will operate depends upon the
precedence and associativity.

Associativity of operators:
When an expression has two operators of equal priority/precedence the tie
between them is settled using the associativity of the operators.
Associativity types:  left to right
 right to left
eg: a = 3/2 * 5
here ‘/’ & * have same priority & both also use left to right associativity.
So ‘/’ or * which one should perform its operation first.
so ‘/’ will be performed first.
‘=’  has R to L associativity so in “a = b = 3”, b = 3 will be operated first.
a = b =c= 3 => a=(b=(c=3))
In arithmetic operators precedence is same as Hierarchy among operators:
1st priority  Parenthesized value(value within bracket or paranthesis): a*(b/(c-d))
2nd priority  *, /, %.
3rd priority  +, -
4th priority  =
Direction of solving (associativity) is from left to right in an expression.
i = 2 * -3 / 4 + 4/4 + 8 -2 + 5%8
Result 
6/4 + 4/4 +8 - 2 + 5/8
12
Anurag Tewari
KIET, GZBD

1 + 4/4 + 8 - 2 + 5/8
1 + 1 + 8 -2 + 5/8
10 – 2 + 0
8+08

A=2+5%7-1*6{Hint: apply brackets to solve as per precedence}


2+(5%7)-(1*6)=2+(5)-(6)=2+5-6=7-6=1

B= 6*-3%-9+18/3-5
=(6*3)%9+(18/3)-5=0+6-5=1

Calculate the results of following expression by applying precedence & associativity rules:
1. a-b/(3+c)*(2-1); a=9,b=12,c=3. Ans:

2. a-(b/(3+c)*2)-1; a=9,b=12,c=3. Ans:4

3. 4+5-55/5%-10 . Ans:8

Precedence :If more than one operators are involved in an expression,


C language has a predefined rule of priority for the operators.
This rule of priority of operators is called operator precedence.

After solving above A=1.

13
Anurag Tewari
KIET, GZBD

Table: Name, Symbol, Category, Precedence and Associativity of Operators

Data-Type Conversion
In any expression if two variables of different data-types are used, then at least one
of them will be converted into another, and then only that operation can be performed.
Two Categories of type conversion –
(A) Implicit
(B) Explicit(type-casting)
(A) Implicit Type Conversion :- When the 2 operands of different types are used in
a binary expression, c compiler automatically converts one type to another, this is called implicit
type conversion.
o This is generally done with the intermediate values during evaluation of expression.
Rules to perform implicit type conversion are as based on hierarchy:

14
Anurag Tewari
KIET, GZBD

Conversion Rank (Hierarchy):

o In assignment expression :
L.H.S. = R.H.S.; then there may be 2 kinds of conversion exists-
Promotion – if the right expression (R.H.S.) has lower rank so it is promoted.
Demotion – if the right expression (R.H.S.) has a higher rank so it is demoted. Demotion occurs only in
assignment operation implicitly.
Since small object can be easily kept in a big box so promotion is always possible but
Reverse is not true.
eg:
char c = ‘A’;
int i = 1234;
long double d = 3458.0004;
now promotion occurs in following independent assignments:

i = c; - value of i = 65
d = i; - value of d is 1234.0000
o So in Demotion – If the size of the variable at the left side can accommodate the value of the
expression, it is O.K. otherwise results may be unpredictable.
eg.: short s = 78;
char c = ‘A’; int j = INT_MAX(=2147483647);
int k = 65;
s=j - value of s may be - unexpected
c = k+1 - demotion : value of c is ‘B’.

Conversion in other Binary Expressions: Summary of rules can be followed in these 3 steps:
1. The operand with the higher rank is determined using the ranking in hierarchy figure
2. The lower-ranked operand is promoted to the rank defined in 1st step. In 2nd step after promotion, both
expressions have same rank.
3. The operation is performed with the expression value having the type of promoted rank.
ex:
char c = ‘A’; int i = 3650; short s = 78;
long double d = 3458. 0004;
i*s; // result is an int
d*c; // result is long double.

In case of demotion type-conversion is done as –


o Float to int causes truncation of the fractional part.
o Double to float causes rounding-off digits.

15
Anurag Tewari
KIET, GZBD

o Long int to int causes dropping of the excess higher order bits.

Example: int i, x;
float f;
double d;
long int L;
x = L / i + i * f - d

float
long
float
long

float
double
double
int
Integer & Float conversions:
(a) Integer {(arithmetic operation)} integer = Integer (result)
(b) Real (float) {(arithmetic opn.)} real (float) = Real (result)
(c) Integer {(arithmetic opn.)} real (float) = Real (float) result.
5.0/2 = 2.50000
5/2 = 2
5/2.0 = 2.5

Explicit conversion :-
o By this we can convert data from one type to another forcefully (not automatically)
o It is done by using a unary operator – cast operator: “( )” and this operation is called-TypeCasting
o To cast (convert) data from one type to another, we specify data-type (new) in parenthesis before the
value we want to convert.
eg.: to convert an integer, a , to a float : (float) a
o Like any other operation, the value of a is still of type int, but the value of the expression is promoted to
float.
General form of explicit conversion is :
(data type-name) expression
ex:
a= (int)21.3/(int)4.5
so result stored in a is 5
y = (int)(a+b), The result of a+b is converted to int.

( float) (a/10) + (float) a/10


int a=3;
(if a=3) 0.0 0.3 printf("%f\n",float(a/10)); =>0.0000
printf("%f\n",(float)a/10); =>0.3000

x= (int) (y+0.5)
If y = 27.6  y +0.5 = 28.1 but after casting x = 28 is stored. So, the result is changed not the
expression
o It is always true that we should use explicit conversion (casting), instead of leaving it on system.

16
Anurag Tewari
KIET, GZBD

main() main()
{ {
float u=3.5; int u=3.5,v,w,x,y;
int v,w,x,y; v=(int)(u+0.5);
v=(int)(u+0.5); w=(int)u+0.5;
w=(int)u+0.5; x=(int)((int)u+0.5);
x=(int)((int)u+0.5); y=(u+(int)0.5);
y=(u+(int)0.5); printf("%d%d%d%d",v,w,x,y);
printf("%d%d%d%d",v,w,x,y); }
}

Output:4333 3333
main() main()
{ {
char aa='c'; int i=5;
int b=97; printf("%d%d%d%d%d",i++,i--,++i,--i,i);
printf("%d",aa+10); }//compiler dependent
printf("\t%c",b-10);
}
45555
Output:109 w

Bit-wise operators
S.No Operator Name of Category ary of Precedence Associativity
Operator Operators amongst
bitwise class
1. ~ Bitwise NOT Unary Unary Level-I R→L

2. << Left Shift Shift Binary Level-II L→R


Right Shift operators
>>
3. & Bitwise AND Bitwise Binary Level-III L→R
operator
4. ^ Bitwise X-OR Bitwise Binary Level-IV L→R
operator
5. | Bitwise OR Bitwise Binary Level-V L→R
operator

Usage of Bitwise Operations or Why to Study Bits

1. Compression: Occasionally, you may want to implement a large number of Boolean variables,
without using a lot of space. A 32-bit int can be used to store 32 Boolean variables. Normally, the

17
Anurag Tewari
KIET, GZBD

minimum size for one Boolean variable is one byte. All types in C must have sizes that are multiples
of bytes. However, only one bit is necessary to represent a Boolean value.

2. Set operations: You can also use bits to represent elements of a (small) set. If a bit is 1, then
element is in the set, otherwise it's not. You can use bitwise AND to implement set intersection,
bitwise OR to implement set union.

3. Encryption: swapping the bits of a string for e.g. according to a predefined shared key will
create an encrypted string.

Properties of Bitwise operators:

 Bitwise operators operate on the individual bits of operands and are used for bit
manipulation.

 They can only be applied on operands of type char, short, int, long, whether signed or
unsigned (never on float/double).

 The bitwise-AND and bitwise-OR operators operate on the individual bits of the operands
according to the truth tables.

18
Anurag Tewari
KIET, GZBD

 EX:The expression 2&3 evaluates to 2 and 2|3 evaluates to 3.

int x=12, y=10 then, printf(“%d”,x&y) will give 8 in decimal. printf(“%d”,x|y) will give 14 in
decimal. printf(“%d”,x^y) will give 6.

19
Anurag Tewari
KIET, GZBD

20
Anurag Tewari
KIET, GZBD

Example: Bitwise complement Operation of 35


~ 00100011
11011100 = 220 (In decimal)
Twist in bitwise complement operator in C Programming
The bitwise complement of 35 (~35) is -36 instead of 220, but why?
For any integer n, bitwise complement of n (~n)will be -(n+1). To understand this, you should have the
knowledge of 2's complement.
2's Complement: Two's complement is an operation on binary numbers. The 2's complement of a number is
equal to the complement of that number plus 1.
Example:
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)

Note: Overflow is ignored while computing 2's complement.


The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the output is -
36 instead of 220.

Bitwise complement of any number N is -(N+1). Here's how:


bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)
Example: Bitwise complement
int main()
{
printf("%d ",~35);
printf("%d",~-12);
return 0;
}
Output: -36 11

Left shift Operator “<<”


The left shift operator will shift the bits of x(decimal no. represented in binary digits) towards left
for the given number of times(n) as x<<n=>x*2n

int a=2<<1;

Let’s take the binary representation:

resentation of 2 assuming int is 1 byte for simplicity.

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 0 1 0
Now shifting the bits towards left for 1 time, will give the following result

21
Anurag Tewari
KIET, GZBD

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0
Now the result in decimal is 4. You can also note that, 0 is added as padding in the position 0.

If you left shift like 2<<2, then it will give the result as 8. Therefore left shifting n times, is
equal to multiplying the value (x) by 2n.

Right shift Operator “>>”


The right shift operator will shift the bits towards right for the given number of times.

int a=8>>1;

Let’s take the binary representation of 8 assuming int is 1 byte for simplicity.

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 1 0 0 0
Now shifting the bits towards right for 1 time, will give the following result

Position 7 6 5 4 3 2 1 0
Bits 0 0 0 0 0 1 0 0
Now the result in decimal is 4. Right shifting 1 time, is equivalent to dividing the value by 2. You
can also note that, 0 is added as padding in the position 7.

Therefore right shifting n times, is equal to dividing the value (x) by 2n.

What does the following code do?


1. int x = 3 ;
2. int n = 2 ;
3. x << n ;
4. printf("%d\n", x) ; O/P will be:3 or 12; ans is 3.
To get answer as 12 change line no. 3 and 4 as:
x = x << n ;
printf("%d\n", x) ;

Note on shifting signed and unsigned numbers


While performing shifting, if the operand is a signed value, then arithmetic shift will be used. If
the type is unsigned, then logical shift will be used.

In case of arithmetic shift, the sign-bit ( MSB ) is preserved. Logical shift will not preserve the
signed bit. Let’s see this via an example.

#include<stdio.h>

22
Anurag Tewari
KIET, GZBD

int main() {
signed char a=-8;
signed char b= a >> 1;
printf("%d\n",b);
}
In the above code, we are right shifting -8 by 1. The result will be “-4″. Here arithmetic shift is
applied since the operand is a signed value.

int main() {
unsigned char a=-8;
unsigned char b= a >> 1;
printf("%d\n",b);
}
Note: Negative number are represented using 2’s complement of its positive equivalent.
2's compliment of +8 is: 1111 1000

Right shifting by 1 yields, 0111 1100 ( 124 in decimal )

The Magic of XOR(+) or ^


Properties of XOR
Here are several useful properties of XOR. This applies to plain XOR and bitwise XOR.
• x (+) 0 = x
XORing with 0 gives you back the same number. Thus, 0 is the identity for XOR.
• x (+) 1 = ~x
XORing with 1 gives you back the negation of the bit. Again, this comes from the truth table.
For bitwise XOR, the property is slightly different: x ^ ~0 = ~x.
That is, if you XOR with all 1's, the result will be the bitwise negation of x.
• x (+) x = 0
XORing x with itself gives you 0. That's because x is either 0 or 1, and 0 (+) 0= 0and 1 (+) 1
= 0.
• XOR is associative.
That is: (x (+) y) (+) z = x (+) (y (+) z).
You can verify this by using truth tables.
• XOR is commutative.
That is: x (+) y = y (+) x.
You can verify this by using truth tables.
Swapping without "temp"
temp = x ;
x=y;
y = temp ;
Now solve this without using a temp variable. This means you can ONLY use x and y. This
does NOT mean that you name the variable temp2.
x=x^y;
23
Anurag Tewari
KIET, GZBD

y=x^y;
x=x^y;
The key to convincing yourself this works is to keep track of the original value of x and y.
Let A be the original value of x(that is, the value x has just before running these three lines of
code).
Similarly, let B be the original value of y.
We can comment each line of code to see what's happening.

// x == A, y == B
x=x^y;
// x == A ^ B, y == B
y=x^y;
// x == A ^ B
// y == (A ^ B) ^ B == A ^ (B ^ B) (by Assoc)
// == A ^ 0 (by z ^ z == 0 property)
// == A (by z ^ 0 == z property)
x=x^y;
// x == ( A ^ B ) ^ A
// == ( A ^ A ) ^ B (by Assoc/Commutativity)
// == 0 ^ B (by z ^ z == 0 property)
// == B (by z ^ 0 == z property)
// y == A
After the second statement has executed, y = A. After the third statement, x = B.

24
Anurag Tewari

You might also like