You are on page 1of 22

TM's

Lecture Notes in C Programming (LNCP)


Unit 1 Part 3
Operators & Expressions
Ver. 1.5
TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

Table of Contents
Classes of C Operators 3
1. Arithmetic operators 3
2. Relational Operators 5
3. Logical Operators 6
4. Assignment Operators(=) 8
5. Increment & Decrement Operators 9
6. Conditional Operator ( ?: ) 10
7. Bitwise Operators 10
8. Special Operators: Comma (,) & sizeof 13

Arithmetic Expressions 13
Expression Evaluation 14
Precedence of Arithmetic Operators: 15
Rules for evaluation of expression 16

Operator Precedence & Associativity (SLE) 17


Operator Precedence 17
Associativity: 17

‘Type conversion’ in expressions 19


1. Implicit Type Conversion: 19
2. Explicit Type Conversion: 22

2 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

Operator
An operator is a symbol that tells the computer to perform some mathematical or logical operation (E.g. +,-,*,/,%,
<, > etc....)

Classes of C Operators
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increments and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

1. Arithmetic operators
Operator Meaning
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus Operator

Integer Arithmetic Operations


Let x = 27 and y = 5 are two integers.
z=x+y 🡺 32
z=x–y 🡺 22
z=x*y 🡺 135
z=x/y 🡺5
z=x%y 🡺2
Modulus Operator gives the remainder of integer division operation of two integers.
E.g: Result of 10%3 is 1, because if you do integer division 10/3 the remainder is 1.
15%5 is equal to 0, since 5 exactly divides 15 and remainder is 0.

3 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

3%10==> 3
5%7 ==> 5
0%5 ==> 0
In general : (0,1,....n-1) % n ==> (0,1,....n-1)
-10%3 ==> -1
-10%-3 ==> -1
10%-3 ==> 1
Note: Sign of the result is the sign of the numerator (The first operand)

Floating point arithmetic


Let x = 14.0 and y = 4.0 then
z=x+y ⇒ 18.0
z=x–y ⇒ 10.0
z=x*y ⇒ 56.0
z=x/y ⇒ 3.50
Note: Modulo-division(%) can not be applied to floating point numbers.

Mixed mode arithmetic


❑ Involving different data types as operands. (Eg. Integer & floating point numbers)
When the operands are of different types, the lower level(precision) operand will be upgraded to higher
level type and then operation is performed. Result will be of the higher precision type.
❑ 15/10.0 ==>1.5
Here 10.0 is floating point type, hence 15 is upgraded as float (i.e 15.0) and then 15.0/10.0 is
performed. Result is 1.5
❑ 15/10 = 1
Since both operands are integers, the result will also be an integer. Hence the actual result is 1,
instead of 1.5 as we would have expected.
❑ int c = 15/10.0; ( c gets value 1)
Here the result of RHS evaluation will be 1.5, But since the result is assigned to an integer type
variable c, 1.5 will be truncated as 1 and stored in c.)

4 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ float f = 25/10; (f gets value 2.0)


In 25/10 both are integers. Hence RHS evaluates to another integer 2 (By truncating 2.5). Since f
at LHS is float type, 2 is elevated as float 2.0. Hence f gets value 2.0.

2. Relational Operators
❑ Used to compare two data values for taking decisions.
< 🡺 less than
<= 🡺 less than or equal to
> 🡺 greater than
>= 🡺 greater than or equal to
== 🡺 equal to
!= 🡺 not equal to
❑ Two possible outcomes for when we apply relational operators on two numeric operands.
1. True 🡺 Represented by value 1
2. False 🡺 Represented by value 0

Example usage of relation operator in a program:


#include<stdio.h>

int main()
{
int age = 25;
if(age > 18)
{
printf("Person can vote");
}
else
{
printf("Person cannot vote");
}
return 0;
}

Output: Person can vote

5 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

3. Logical Operators
Logical operators in C.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
❑ Mainly used to check more than one condition to take decisions (&& and ||).
LOGICAL AND operator(&&)
Usage: Exp1 && Exp2
❑ If Both LHS and RHS expressions are individually True, then only the final outcome is True. In all
other cases, the final outcome is False.
❑ Example usage:
int age = 25,salary = 10000;
if(age < 30 && salary>25000)
{
//If both conditions are true, this section is executed
printf(“Person is well paid”);
}
else
{
printf(“Person is under-paid”);
}

Output(Truth table) of LOGICAL AND operator(&&)


Usage: Exp1 && Exp2
Exp1 Exp2 Exp1 && Exp2
0 0 0
0 NZ 0
NZ 0 0
NZ NZ 1

NZ ==> Non-zero
In summary, for TRUE(1) output, both expressions must be NON-ZERO

LOGICAL OR operator(||)
Usage: Eg: Exp1 || Exp2

6 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

If both LHS and RHS expressions are False, the final outcome is False. In All other cases the final
outcome is True.
int age = 70;
if(age < 13 || age >60)
{
//If any 1 condition is true, this section is executed
printf(“Need special care\n”);
}
else
{
// If both conditions are false. This section executed
printf(“No need of special care\n”);
}

Output(Truth table) of LOGICAL OR operator( || )


Exp1 Exp2 Exp1 || Exp2
0 0 0
0 NZ 1
NZ 0 1
NZ NZ 1

NZ ==> Non-zero
In summary, Result is TRUE, if either of the expressions or both expressions are NON-ZERO (True).
FALSE only when both exp1 and exp2 are False.

LOGICAL NOT operator (!)


It is a unary operator. i.e only one operand is there for this operator. So far, all operators we studied were
all binary operators which had 2 operands.
The operand for Logical NOT is expected to a Boolean value 1 or 0(True or False). Any Non-zero value
is treated as True and 0 is treated as False.
Hence !5 is 0. !0 is 1. !1 is 0
Logical NOT operator negates the operands value.
int a = 10;
a<18; // result: 1
!(a<18); // result: 0

Normally used in Decision making


if( !(age<18) )

7 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

printf(“Person can vote.”);


!(age<18) is equivalent to age>=18. Either of these can be used in programs.
Output(Truth table) of LOGICAL NOT operator( ! )
Exp !Exp
NZ 0
0 1
4. Assignment Operators(=)
❑ Basic assignment operator (=) Assign value of RHS expression to variable on LHS
General Syntax: var = exp;
E.g: a=5; b= c+5; d = a+b*c;

❑ Shorthand Assignment Operators( +=, -+, *=, /=, %= )


These operators combine an arithmetic operation with assignment.
E.g.
a = a+5; can be written as a+=5;
a= a*b; can written as a*=b;
Shorthand assignment operators are generally used when the LHS variable is appearing in RHS
expression as in a = a+10; (Here LHS variable a is appearing in RHS expression.)
General Syntax : variable op= exp;
E.g:
a+=5; // Equivalent to a = a+5;
a*=b; // Equivalent to a = a*5;
a%=3; // Equivalent to a = a%3;

Assignment Shorthand Assignment


❑ a=a+1 a += 1
❑ a=a–1 a -= 1
❑ a = a * (n+1) a *= (n+1)
❑ a = a / (n+1) a /= (n+1)
❑ a=a%b a %= b

8 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

Shorthand assignment operator Advantages


❑ LHS need not be repeated (instead of a= a+5 simply a+=5)
❑ Statement is concise.
❑ Statement is more efficient.

5. Increment & Decrement Operators


❑ ++, - - 🡺 They are unary operators(Only one operand)
❑ ++ 🡺 Increase value of variable by 1.
❑ Can only be applied to variables(Not on constants or expressions)
Usage: (Let v be a variable)
❑ 1. ++v 🡺 Prefix Increment : Effect is same as v = v + 1;
❑ 2. v++ 🡺 Postfix Increment : Effect is same as v = v + 1;
❑ 3. --v 🡺 Prefix Decrement : Effect is same as v = v - 1;
❑ 4. v-- 🡺 Postfix Decrement : Effect is same as v = v - 1;
When used this way independently as above, prefix and postfix forms of ++ and -- does not make any
difference in the program. But when used in expressions of the form below it can make a difference.
Examples:
m = 5;
y = ++m; // prefix increment
❑ After Execution: y=6, m=6
m = 5;
y = m++; // postfix increment
❑ After Execution: y=5, m=6
❑ Hence prefix increment first increments the value of the variable and the new value is used in the
expression. But in case of postfix increment, first the existing value of the operand variable is used
in the expression and then incremented. Understanding this difference is important.
Rules for increment and decrement operators:
❑ ++,-- are Unary operators, these work only on variables, not on constants(E.g. 5++ is wrong,
num++ is valid).
❑ Postfix ++(--)used in expression first value is used in evaluation of expression, then
incremented(decremented).

9 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ Prefix ++(--)used in expression first variable incremented(decremented), the new value is used in
evaluation of expression,
❑ Precedence and associativity of ++ and -- are same as that of unary + and unary –

6. Conditional Operator ( ?: )
It is a ternary operator in C. I.e, it has got three operands.

❑ General Syntax: exp1?exp2:exp3;


❑ Exp1 is evaluated first.
❑ If exp1 evaluates to a true(i.e any non-zero value) then exp2 is evaluated.
❑ Otherwise, If exp1 evaluates to a false (i.e. zero) then exp3 is evaluated.
❑ exp1?exp2:exp3 has the same effect as the following.
if(exp1)
exp2;
else
exp3;

Example 1:
❑ a = 10; b=15;
❑ x = (a>b)?a:b; // x ⇐ 15; i.e The expression finds larger of two numbers.
❑ The above line has the same effect as the following.
if(a>b)
x = a;
else
x = b;
❑ Conditional Operator is a concise way of doing if-else condition.
❑ It can reduce the number of lines of code in a program. In the above example four lines of code are
reduced to one line by use of conditional operator.

7. Bitwise Operators
❑ Act on bit level in a data item(integer variable, int constant etc.)
❑ Can’t work on floating point number(real numbers)
❑ Operators are:

10 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ << 🡺 Shift left


❑ >> 🡺 Shift right
❑ & 🡺 Bitwise AND
❑ | 🡺 Bitwise OR
❑ ^ 🡺 Bitwise Exclusive OR

Shift left operator (<<)


❑ Examples(shift left: <<): (Assume integer variable is 1 byte size)
❑ int a = 5;

a’s Bit Sequence in Memory


❑ b = a<<1; // Shift the bits of variable a one position left and assign to b.

b's Bit Sequence in Memory


❑ a's bit sequence remains same as original.
❑ c = a<<2; // Shift the bits of variable a, 2 positions left and assigned it to c.

` c's bit Sequence in Memory:


❑ Now what are the decimal values of a , b & c?? (5, 10 & 20 respectively. Is it causing a multiply
by 2 effect? )
Shift right operator (>>)
❑ Examples(shift right >>): (Assume integer variable is 1 byte size. )
❑ int a = 5;

11 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

a‘s Bit Sequence in Memory


❑ Operators are:
❑ b = a>>1; // Shift the bits one position right and assign to b.

b‘s Bit Sequence in Memory


❑ a‘s bit sequence remains same as original.
❑ Decimal values of a & b? (5 & 2. Is it causing a divide by 2 effect? )
Bitwise AND Operator (&)
❑ Examples(Bitwise AND :&): (Assume integer variable is 1 byte size)
❑ int a = 5,b = 6,c;
❑ a‘s Bit Sequence in Memory ⇒
❑ b‘s Bit Sequence in Memory ⇒
❑ c = a & b;
❑ c‘s Bit Sequence in Memory ⇒

Bitwise OR Operator( | )
Examples(Bitwise OR:|): (Assume integer variable is 1 byte size)
❑ int a = 5,b = 6,c;
❑ a’s Bit Sequence in Memory⇒

❑ b’s Bit Sequence in Memory⇒

❑ c = a | b;
❑ c‘s Bit Sequence in Memory⇒

Bitwise XOR Operator(^)


❑ Examples(Bitwise XOR:^): (Assume integer variable is 1 byte size)
❑ int a = 5, b = 6,c;

12 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ a's Bit Sequence in Memory:


❑ b's Bit Sequence in Memory:

❑ c = a ^ b;
❑ c‘s Bit Sequence in Memory:

8. Special Operators: Comma (,) & sizeof


1. Comma operator ( ,)
❑ Used to link related expressions together.
❑ Comma separated expressions execute from left to right.
❑ Right most expression is the value of the combined expression.
E.g: v = (x=10, y=5, x+y);
Value of v?
E.g. for loop: for(i=0,j=1; i<n; i++,j++)
2. Special Operators: sizeof
❑ Used to find the size(in bytes) of a data type or variable or constant.
❑ int a = sizeof(int); // a??
❑ int b = sizeof(float); // b??
❑ int c = sizeof(a); // c??
❑ int d = sizeof(100); // d??

Arithmetic Expressions
An arithmetic expression is a combination of variables, constants and operators arranged as per syntax of
the language.
❑ Following are some mathematical expressions and their equivalent arithmetic expressions in C.

13 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

Evaluation of expressions
❑ General format:
variable = expression;
❑ First expression is evaluated fully, then the result is assigned to the variable in LHS.
❑ x = a * b - c;
❑ y = b / c *a;
❑ z = a – b / c + d;
Expression Evaluation
Expressions are evaluated using an assignment statement of the form:

In the above syntax, variable is any valid C variable name. When the statement like the above form is
encountered, the expression is evaluated first and then the value is assigned to the variable on the left
hand side. All variables used in the expression must be declared and assigned values before evaluation is
attempted. Examples of expressions are:

14 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

Precedence & Associativity of most common operators

Precedence of Arithmetic Operators:


Precedence refers to the relative priority assumed for the operators that determines the order of execution
of the sub-expressions of a compound expression.
Consider the following code:
int a = 2,b = 4,c=5,d=3;
int e = a+b*c/d;
❑ In the above code, the order of executing sub-expressions affects the final result.
❑ If the expression is executed from left to right in-indiscriminately, a+b is done first, the result is
multiplied with c and the result of that is divided with d. The result will be 10.
❑ But the correct result in e is 8. ( b*c = 20, 20/d = 6, a+6 = 8 (Final result in e)
❑ C language defines rules for deciding the order execution in such complex expressions.

15 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ Precedence: refers to the priority of operators w.r.t choosing order of execution.


❑ High Precedence: * / %
❑ Low Precedence: + -
Let us try to evaluate an arithmetic expression as shown below:

❑ x = a-b/3+c*2-1
❑ Let a = 9, b =12, and c=3. Then our expression becomes:

❑ x = 9-12/3+3*2-1
❑ From the table in previous page, we can see that the * and / operators are having higher
precedence than + and – operators. Also, the * and / operators are at the same level of precedence,
so we have to apply the associativity rules. Since the associativity rule is left-to-right for
arithmetic operators, we apply the / operator first and the expression evaluates to:

❑ x = 9-4+3*2-1
❑ Next, we apply the * operator and the expression becomes:

❑ x = 9-4+6-1
❑ Next, we apply the first – operator as the – and + operators are at the same level and the
associativity rule is from left to right. The expression becomes:

❑ x = 5+6-1
❑ Now, we apply the + operator and the expression become:

❑ x = 11-1
❑ Finally, we apply the – operator and the result is:
❑ x = 10

Rules for evaluation of expression


E.g expression: (x+y)*a+b/c+(x-y)-(a*b+(c+d))
1. First, parenthesized subexpressions(e.g. x+y, x-y etc.) from left to right are evaluated.
2. If parentheses are nested ( e.g. (a*b+(c+d)) ), the evaluation begins with the innermost
subexpression.
3. The precedence rule is applied in determining the order of application of operators in evaluating
subexpressions
4. The associatively rule is applied when 2 or more operators of the same precedence level appear in
a subexpression.

16 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

5. Arithmetic expressions are evaluated from left to right using the rules of precedence
6. When parentheses are used, the expressions within parentheses assume highest priority

Operator Precedence & Associativity (SLE)


Every C operator has a precedence (priority) associated with it. This precedence is used to
determine how an expression involving more than one operator is evaluated. There are different levels of
operator precedence and an operator may belong to any one of these levels. The operators at the higher
level of precedence are evaluated first.
The operators in the same level of precedence are evaluated from left to right or from right to
left, based on the associativity property of an operator. In the below table we can look at the precedence
levels of operators and also the associativity of the operators within the same level. Rank 0 indicates the
lowest precedence and Rank 14 indicates highest precedence.

​Operator Precedence
❑ All operators are classified into different levels of precedence.
❑ If expression involves multiple operators(e.g: a+b*c-d), operation with higher precedence is
performed first.
❑ ‘b*c’ is done first in the example, since * has higher precedence than +,-
❑ What if the precedence for two operators are the same? ?
❑ I.e, in example a+b*c-d , + and – have the same precedence.
❑ The answer is: Associativity

​Associativity:
❑ Associativity : Defines the direction of execution when operators of the same precedence level are
involved.
❑ Two types of associativity:
Left-to-right associativity(L-R)
Right-to-left associativity(R-L)
❑ Arithmetic operators follow L-R associativity.

E.g.:

17 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ First b*c is computed due higher precedence of * over + and -.


❑ Then since + and – have the same precedence. Hence using Left to Right Associativity, +
operation is done with a and result of b*c. Then subtraction is done on the result and d.
❑ Precedence rules can be bypassed with use of parentheses
❑ E.g. (a+b)*c-d
Precedence & Associativity table

Precedence & Associativity

18 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

❑ E.g. a+b*c-e*f
❑ E.g. if(a>b && c==d)
❑ E.g. a=5, b=10; !a<b (Note: ! has higher precedence than <)
❑ (a*b)*(c-d)/(e+f)
❑ Precedence rules decide the order in which different precedence level operators are applied.
❑ Associativity rules decide the order in which operators in same precedence level are applied.

‘Type conversion’ in expressions


❑ Conversion of one data type to another. When variables and constants of different types are
combined in an expression then they are converted to the same data type. The process of
converting one predefined type into another is called Type Conversion.
❑ Type Conversion is also known as Type Casting
❑ Done when expressions contains operands of different types.
E.g: 2+3*2.7+7 . here 2.7 is a floating point type and others are intergers.

Two types of type conversions

​1. Implicit Type Conversion:


Automatically done by the compiler.
❑ This conversion happens according to the rules of the language.
❑ General thumb rule for ‘automatic’ type conversion: Conversion done such a way that, there is
no data/precision loss.

Entire Data Types in C (Primary types + Modification of primary types) based on 16-bit system
architecture.

19 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

The sequence of rules that are applied while evaluating expressions are given below:All short and char are
automatically converted to int, then,

1. If either of the operands is of type long double, then others will be converted to long double and
result will be long double.
2. Else, if either of the operands is double, then others are converted to double.
3. Else, if either of the operands is float, then others are converted to float.
4. Else, if either of the operands is unsigned long int, then others will be converted to unsigned long
int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
a. if a long int can represent all values of an unsigned int, the unsigned int is converted to
long int.
b. otherwise, both operands are converted to unsigned long int & result is long int.
6. Else, if either operand is long int then other will be converted to long int & result is long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int & result is long
int.

Implicit Type Conversion hierarchy

20 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

Format Specifier for different Data type ( w.r.t GNU C Compiler(GCC) )

short int ==> %hi or %hd


char ==> %c
int ==> %d
unsigned int ==> %u
long int ==> %ld
unsigned long int ==> %lu
float ==> %f
double ==> %lf
long double ==>%Lf

Example:
int i,x;
float f;
double d;
longint t;

x = t/i + i*f – d;

1. First t/i is considered. Since i is int type and t is long type, i is automatically converted to long
and result is a long type.
2. Next i*f is evaluated, iint and f is float, hence i is converted to float and result is also a float.
3. Result of step 1(long type) is added to the result of step 2(float type), and the result is float .
Because float is of higher precision(level) than long.

21 (For non-commercial educational use only)


TM’s C Programming Lecture Notes v.1.5 Operators & Expressions

4. Remaining computation is (Result of step 3 - d). Since d is double, which is of higher precision
than float, Result of step 3 is elevated from float to double and subtraction is performed. The result is a
double.
5. The result is finally assigned to int type variable x (x = ........) Hence double value is truncated
to an integer type (E.g if the result of RHS computation was 76.3444 it will be truncated to 76 and stored
in x)

These steps are depicted in the following diagram.

​2. Explicit Type Conversion:


Explicitly done using casting operator
Syntax: variable = (type)expression; // variable/expression
int a =10;
float b;
b = (float)a; // explicit type conversion

❑ Another example
int a = 5,b =3;
float c = a/b; // c = 1.0
float d = (float)a/b; // d = 1.666667 . Here, a is first converted to float. Then the
operation is performed

22 (For non-commercial educational use only)

You might also like