OPERATORS AND EXPRESSIONS
By Paribesh Sapkota
Operators : An operator is a Symbol that performs an operation. An operators acts some variables are called operands to get the desired result.
Ex : a+b;
Where a,b are operands and + is the operator.
Types of Operator :
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
5). Unary Operators.
6) Conditional Operators.
7) Special Operators.
8) Bitwise Operators.
9) Shift Operators.
Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and multiplication on numerical values (constants and variables).
C Program to demonstrate the working of arithmetic operators
#include <stdio.h> void main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d \n",c); c = a-b; printf("a-b = %d \n",c); c = a*b; printf("a*b = %d \n",c); c=a/b; printf("a/b = %d \n",c); c=a%b; printf("Remainder when a divided by b = %d \n",c); }
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
Relational Operators. A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.
Operands may be variables, constants or expressions.
Relational operators are used in decision making and loops.
Operator | Meaning | Example | Return value |
< | is less than | 2<9 | 1 |
< = | is less than or equal to | 2 < = 2 | 1 |
> | is greater than | 2 > 9 | 0 |
> = | is greater than or equal to | 3 > = 2 | 1 |
= = | is equal to | 2 = = 3 | 0 |
!= | is not equal to | 2!=2 | 0 |
// C Program to demonstrate the working of relational operators #include <stdio.h> int main() { int a = 5, b = 5, c = 10; printf("%d == %d = %d \n", a, b, a == b); // true printf("%d == %d = %d \n", a, c, a == c); // false printf("%d > %d = %d \n", a, b, a > b); //false printf("%d > %d = %d \n", a, c, a > c); //false printf("%d < %d = %d \n", a, b, a < b); //false printf("%d < %d = %d \n", a, c, a < c); //true printf("%d != %d = %d \n", a, b, a != b); //false printf("%d != %d = %d \n", a, c, a != c); //true printf("%d >= %d = %d \n", a, b, a >= b); //true printf("%d >= %d = %d \n", a, c, a >= c); //false printf("%d <= %d = %d \n", a, b, a <= b); //true printf("%d <= %d = %d \n", a, c, a <= c); //true return 0; }
Output
5 == 5 = 1
5 == 10 = 0
5 > 5 = 0
5 > 10 = 0
5 < 5 = 0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
Logical Operators.
These operators are used to combine the results of two or more conditions. An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.
Operator | Meaning | Example | Return value |
&& | Logical AND | (9>2)&&(17>2) | 1 |
|| | Logical OR | (9>2) || (17 = = 7) | 1 |
! | Logical NOT | 29!=29 | 0 |
Logical AND : If any one condition false the complete condition becomes false.
Truth Table
Op1 | Op2 | Op1 && Op2 |
true | true | true |
true | false | false |
false | true | false |
false | false | false |
Logical OR : If any one condition true the complete condition becomes true.
Truth Table
Op1 | Op2 | Op1 // Op2 |
true | true | true |
true | false | true |
false | true | true |
false | false | false |
Logical Not : This operator reverses the value of the expression it operates on i.e, it makes a true expression false and false expression true.
Op1 | Op1 ! |
true | false |
false | true |
// C Program to demonstrate the working of logical operators #include <stdio.h> C PROGRAMMING Page 34 int main() { int a = 5, b = 5, c = 10, result; result = (a = b) && (c > b); printf("(a = b) && (c > b) equals to %d \n", result); result = (a = b) && (c < b); printf("(a = b) && (c < b) equals to %d \n", result); result = (a = b) || (c < b); printf("(a = b) || (c < b) equals to %d \n", result); result = (a != b) || (c < b); printf("(a != b) || (c < b) equals to %d \n", result); result = !(a != b); printf("!(a == b) equals to %d \n", result); result = !(a == b); printf("!(a == b) equals to %d \n", result); return 0; }
Output
(a = b) && (c > b) equals to 1
(a = b) && (c < b) equals to 0
(a = b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
Assignment Operators. Assignment operators are used to assign a value (or) an expression (or) a value of a variable to another variable.
Syntax : variable name=expression (or) value (or) variable
Ex : x=10;
y=a+b;
z=p;
Compound assignment operator:
„C‟ provides compound assignment operators to assign a value to variable in order to assign a new value to a variable after performing a specified operation.
Operator | Example | Meaning |
+ = | x + = y | x=x+y |
– = | x – = y | x=x-y |
* = | x * = y | x=x*y |
/ = | x / = y | x=x/y |
% = | x % = y | X=x%y |
// C Program to demonstrate the working of assignment operators #include <stdio.h> int main() { int a = 5, c; c = a; C PROGRAMMING Page 36 printf("c = %d \n", c); c += a; // c = c+a printf("c = %d \n", c); c -= a; // c = c-a printf("c = %d \n", c); c *= a; // c = c*a printf("c = %d \n", c); c /= a; // c = c/a printf("c = %d \n", c); c %= a; // c = c%a printf("c = %d \n", c); return 0; }
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
Increment and Decrement Operators /Unary Operators:
Unary operators are having higher priority than the other operators. Unary operators, meaning they only operate on a single operand.
Increment Operator in C Programming
- Increment operator is used to increment the current value of variable by adding integer 1. 2. Increment operator can be applied to only variables.
- Increment operator is denoted by ++.
We have two types of increment operator i.e Pre-Increment and Post-Increment Operator. Pre-Increment
Pre-increment operator is used to increment the value of variable before using in the expression. In the Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable „y‟ is 5 then value of variable „b‟ will be 6 because the value of „y‟ gets modified before using it in a expression.
Post-Increment
Post-increment operator is used to increment the value of variable as soon as after executing expression completely in which post increment is used. In the Post-Increment value is first used in a expression and then incremented.
b = x++;
In this example suppose the value of variable „x‟ is 5 then value of variable „b‟ will be 5 because old value of „x‟ is used.
Note :
We cannot use increment operator on the constant values because increment operator operates on only variables. It increments the value of the variable by 1 and stores the incremented value back to the variable
C PROGRAMMING Page 38
b = ++5;
or
b = 5++;
The syntax of the operators is given below.
++<variable name> –<variable name>
<variable name>++ <variable name>–
The operator ++ adds 1 to the operand and – subtracts 1 from the operand. These operators in two forms : prefix (++x) and postfix(x++).
Operator | Meaning |
++x | Pre increment |
– -x | Pre decrement |
x++ | Post increment |
x– | Post decrement |
Where
1 : ++x : Pre increment, first increment and then do the operation.
2 : – -x : Pre decrement, first decrements and then do the operation.
3 : x++ : Post increment, first do the operation and then increment.
4 : x- – : Post decrement, first do the operation and then decrement.
// C Program to demonstrate the working of increment and decrement operators #include <stdio.h> int main() { int a = 10, b = 100; float c = 10.5, d = 100.5; printf("++a = %d \n", ++a); printf("--b = %d \n", --b); printf("++c = %f \n", ++c); printf("--d = %f \n", --d); return 0; }
Output
++a = 11
–b = 99
++c = 11.500000
++d = 99.500000
Multiple increment operators inside printf
#include<stdio.h> void main() { int i = 1; printf("%d %d %d", i, ++i, i++); }
Output : 3 3 1
Pictorial representation
Explanation of program
I am sure you will get confused after viewing the above image and output of program. 1. Whenever more than one format specifiers (i.e %d) are directly or indirectly related with same variable (i,i++,++i) then we need to evaluate each individual expression from right to left.
- As shown in the above image evaluation sequence of expressions written inside printf will be – i++,++i,i
- After execution we need to replace the output of expression at appropriate place
No | Step | Explanation |
1 | Evaluate
i++ |
At the time of execution we will be using older value of i = 1 |
2 | Evaluate
++i |
At the time of execution we will be increment value already modified after step 1 i.e i = 3 |
2 | Evaluate i | At the time of execution we will be using value of i modified in step 2 |
Postfix and Prefix Expression in Same Statement
#include<stdio.h> #include<conio.h> void main() { int i = 0, j = 0; j = i++ + ++i; printf("%d\n", i); printf("%d\n", j); }
Output :
2
2
Explanation of Program
Conditional Operator/ Ternary operator:
conditional operator checks the condition and executes the statement depending of the condition. A conditional operator is a ternary operator, that is, it works on 3 operands. Conditional operator consist of two symbols.
1 : question mark (?).
2 : colon ( : ).
C PROGRAMMING Page 41
Syntax : condition ? exp1 : exp2;
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition is false (zero) then the “exp2” is evaluated.
#include <stdio.h> int main(){ char February; int days; printf("If this year is leap year, enter 1. If not enter any integer: "); scanf("%c",&February); // If test condition (February == 'l') is true, days equal to 29. // If test condition (February =='l') is false, days equal to 28. days = (February == '1') ? 29 : 28; printf("Number of days in February = %d",days); return 0; }
Output
If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29
Bitwise Operators:
Bitwise operators are used to manipulate the data at bit level. It operates on integers only. It may not be applied to float.In arithmetic-logic unit (which is within the CPU), mathematical operations like: addition, subtraction, multiplication and division are done in bit-level which makes processing faster and saves power. To perform bit-level operations in C programming, bitwise operators are used.
Operator | Meaning |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
< < | Shift left |
> > | Shift right |
~ | One‟s complement. |
Bitwise AND operator &
The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
C PROGRAMMING Page 42
Bit Operation of 12 and 25
00001100
& 00011001
________
00001000 = 8 (In decimal)
Example #1: Bitwise AND
#include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a&b); return 0; }
Output
Output =8
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
Example #2: Bitwise OR
#include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a|b); return 0; C PROGRAMMING Page 43 }
Output
Output =29
Bitwise XOR (exclusive OR) operator ^
The result of bitwise XOR operator is 1 if the corresponding bits of two operands are opposite. It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25
00001100
| 00011001
________
00010101 = 21 (In decimal)
Example #3: Bitwise XOR
#include <stdio.h> int main() { int a = 12, b = 25; printf("Output = %d", a^b); return 0; }
Output
Output = 21
Bitwise complement operator ~
Bitwise compliment operator is an unary operator (works on only one operand). It changes 1 to 0 and 0 to 1. It is denoted by ~.
35 = 00100011 (In Binary)
Bitwise complement Operation of 35
C PROGRAMMING Page 44
~ 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 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. For 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 #4: Bitwise complement
#include <stdio.h> int main() { printf("complement = %d\n",~35); printf("complement = %d\n",~-12); return 0; }
Output
Complement = -36
Complement = 11
There are two Bitwise shift operators in C programming:
∙ Right shift operator
∙ Left shift operator.
Right Shift Operator
Right shift operator shifts all bits towards right by certain number of specified bits. It is denoted by >>.
Left Shift Operator
Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by <<.
Special Operators
1 ) Comma Operator :The comma operator is used to separate the statement elements such as variables, constants or expressions, and this operator is used to link the related expressions together, such expressions can be evaluated from left to right and the value of right most expressions is the value of combined expressions
Ex : val(a=3, b=9, c=77, a+c)
First signs the value 3 to a, then assigns 9 to b, then assigns 77 to c, and finaly80(3+77) to value.
C PROGRAMMING Page 46
2 ) Sizeof Operator : The sizeof() is a unary operator, that returns the length in bytes o the specified variable, and it is very useful to find the bytes occupied by the specified variable in the memory.
Syntax : sizeof(variable-name);
int a;
Ex : sizeof(a); //OUTPUT—–2bytes
Example #6: sizeof Operator
#include <stdio.h> int main() { int a, e[10]; float b; double c; char d; printf("Size of int=%lu bytes\n",sizeof(a)); printf("Size of float=%lu bytes\n",sizeof(b)); printf("Size of double=%lu bytes\n",sizeof(c)); printf("Size of char=%lu byte\n",sizeof(d)); printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e)); return 0; }
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Size of integer type array having 10 elements = 40 bytes
Expressions
Expressions : An expression is a combination of operators and operands which reduces to a single value. An operator indicats an operation to be performed on data that yields a value. An operand is a data item on which an operation is performed.
A simple expression contains only one operator.
Ex : 3+5 is a simple expression which yields a value 8, -a is also a single expression. A complex expression contain more than one operator.
C PROGRAMMING Page 47
Ex : complex expression is 6+8*7.
Ex ; Algeberic Expressions C-expression
1 : ax2+bx+c 1: a*x*x+b*x+c
2 : a+bx 2 : a+b*x.
3 : 4ac/b 3 : 4*a*c/b.
4 : x2/y2-1 4 : x*x/y*y-1
Operator Precedence : Arithmetic Operators are evaluvated left to right using the precedence of operator when the expression is written without the paranthesis.They are two levels of arithmetic operators in C.
1 : High Priority * / %
2 : Low Priority + -.
Arithmetic Expression evaluation is carried out using the two phases from left to right.
1 : First phase : The highest priority operator are evaluated in the 1st phase. 2 : Second Phase : The lowest priority operator are evaluated in the 2nd phase.
Ex : a=x-y/3+z*2+p/4.
x=7, y=9, z=11, p=8.
a= 7-9/3+11*2+8/4.
1st phase :
1 : a = 7-3+11*2+8/4
2 : a = 7-3+22+8/4
3 : a = 7-3+22+2
2nd phase :
1 : a = 4+22+2
2 : a = 26+2
3 : a = 28
The order of evaluation can be changed by putting paranthesis in an expression. Ex : 9-12/(3+3)*(2-1)
Whenever parentheses are used, the expressions within parantheses highest priority. If two or more sets of paranthesis appear one after another. The expression contained in the left-most set is evaluated first and the right-most in the last.
1st phase :
1 : 9-12/6*(2-1)
2 : 9-12/6*1
2nd phase :
1 : 9-2*1
2 : 9-2.
3rd phase :
1 : 7.
Rules for Evaluation of Expression :
1 : Evaluate the sub-expression from left to right. If parenthesized.
2 : Evaluate the arithemetic Expression from left to right using the rules of precedence. 3 : The highest precedence is given to the expression with in paranthesis.
4 : When parantheses are used, the expressions within parantheses assume highest priority. 5 : Apply the associative rule, if more operators of the same precedence occurs.
Operator Precedence and Associativity :
Every operator has a precedence value. An expression containing more than one oerator is known as complex expression. Complex expressions are executed according to precedence of operators.
Associativity specifies the order in which the operators are evaluated with the same precedence in a complex expression. Associativity is of two ways, i.e left to ringht and right to left. Left to right associativity evaluates an expression starting from left and moving towards right. Right to left associativity proceds from right to left.
The precedence and associativity of various operators in C.
Operator | Description | Precedence | Associativity |
( )
[ ] |
Function call
Square brackets. |
1 | L-R (left to right) |
+
– ++ — ! ~ * & sizeof |
Unary plus
Unary minus Increment Decrement Not operator Complement Pointer operator Address operator Sizeof operator |
2 | R-L (right to left) |
*
/ % |
Multiplication
Division Modulo division |
3 | L-R (left to right) |
+
– |
Addition
Subtraction |
4 | L-R (left to right) |
<<
>> |
Left shift
Right shift |
5 | L-R (left to right) |
< <= > >= | Relational Operator | 6 | L-R (left to right) |
= =
!= |
Equality
Inequality |
7 | L-R (left to right) |
& | Bitwise AND | 8 | L-R (left to right) |
^ | Bitwise XOR | 9 | L-R (left to right) |
| | Bitwise OR | 10 | L-R (left to right) |
&& | Logical AND | 11 | L-R (left to right) |
| | | Logical OR | 12 | L-R (left to right) |
?: | Conditional | 13 | R-L (right to left) |
= *= /= %= += -= &= ^= <<= >>= | Assignment operator | 14 | R-L (right to left) |
, | Comma operator | 15 | L-R (left to right) |
Type Conversion/Type casting:
Type conversion is used to convert variable from one data type to another data type, and after type casting complier treats the variable as of new data type.
For example, if you want to store a ‘long’ value into a simple integer then you can type cast ‘long’ to ‘int’. You can convert the values from one type to another explicitly using the cast operator. Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator.
Syntax:
(type_name) expression;
Without Type Casting:
- int f= 9/4;
- printf(“f : %d\n”, f );//Output: 2
With Type Casting:
- float f=(float) 9/4;
- printf(“f : %f\n”, f );//Output: 2.250000
Example:
#include <stdio.h> int main() { printf( "%c\n", (char)65 ); getchar(); }
Type conversion in c can be classified into the following two types:
- Implicit Type Conversion
When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion.
int x;
for(x=97; x<=122; x++)
{
printf(“%c”, x); /*Implicit casting from int to char thanks to %c*/
}
- Explicit Type Conversion
The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion. The explicit type conversion is also known as type casting.
C PROGRAMMING Page 51
Type casting in c is done in the following form:
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, variable or expression.
For example,
int x;
for(x=97; x<=122; x++)
{
printf(“%c”, (char)x); /*Explicit casting from int to char*/
}
The following rules have to be followed while converting the expression from one type to another to avoid the loss of information:
All integer types to be converted to float.
All float types to be converted to double.
All character types to be converted to integer.
Example
Consider the following code:
int x=7, y=5 ;
float z;
z=x/y; /*Here the value of z is 1*/
If we want to get the exact value of 7/5 then we need explicit casting from int to float:
C PROGRAMMING Page 52
int x=7, y=5;
float z;
z = (float)x/(float)y; /*Here the value of z is 1.4*/
Integer Promotion
Integer promotion is the process by which values of integer type “smaller” than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character with an integer −
#include <stdio.h> main() { int i = 17; char c = 'c'; /* ascii value is 99 */ int sum; sum = i + c; printf("Value of sum : %d\n", sum ); }
When the above code is compiled and executed, it produces the following result − Value of sum : 116
Here, the value of sum is 116 because the compiler is doing integer promotion and converting the value of ‘c’ to ASCII before performing the actual addition operation.
Expression
Most of the statements in a C program are expression statements. An expression statement is simply an expression followed by a semicolon. The lines
i = 0;
i = i + 1;
and printf(“Hello, world!\n”);
are all expression statements. In C, however, the semicolon is a statement terminator. Expression statements do all of the real work in a C program. Whenever you need to compute new values for variables, you’ll typically use expression statements (and they’ll typically contain assignment operators). Whenever you want your program to do something visible, in the real world, you’ll typically call a function (as part of an expression statement). We’ve already seen the most basic example: calling the function printf to print text to the screen.
Note –If no expression is present, the statement is often called the null statement. Return
The return statement terminates execution of a function and returns control to the calling function, with or without a return value. A function may contain any number of return statements. The return statement has
syntax: return expression(opt);
If present, the expression is evaluated and its value is returned to the calling function. If necessary, its value is converted to the declared type of the containing function’s return value.
A return statement with an expression cannot appear in a function whose return type is void . If there is no expression and the function is not defined as void , the return value is undefined. For example, the following main function returns an unpredictable value to the operating system:
main ( )
{
return;
}