Operators
Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
We will, in this chapter, look into the way each operator works. Here, you
will get an overview of all these chapters. Thereafter, we have provided
independent chapters on each of these operators that contain plenty of
examples to show how these operators work in C Programming.
Arithmetic Operators
We are most familiar with the arithmetic operators. These operators are
used to perform arithmetic operations on operands. The most common
arithmetic operators are addition (+), subtraction (-), multiplication (*),
and division (/).
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then −
Show Examples
Advertisement
Relational Operators
The most common relational operators are less than (<), greater than
(>), less than or equal to (<=), greater than or equal to (>=), equal to
(==), and not equal to (!=). Relational operators are also binary
operators, needing two numeric operands.
We shall learn more about with relational operators and their usage in one
of the following chapters.
Show Examples
(A == B)
Checks if the values of two operands are equal or not. If yes, then the
== is not
condition becomes true.
true.
Checks if the values of two operands are equal or not. If the values are (A != B)
!=
not equal, then the condition becomes true. is true.
Checks if the value of left operand is greater than the value of right (A > B) is
>
operand. If yes, then the condition becomes true. not true.
Checks if the value of left operand is less than the value of right operand. (A < B) is
<
If yes, then the condition becomes true. true.
(A >= B)
Checks if the value of left operand is greater than or equal to the value of
>= is not
right operand. If yes, then the condition becomes true.
true.
Checks if the value of left operand is less than or equal to the value of (A <= B)
<=
right operand. If yes, then the condition becomes true. is true.
Logical Operators
The most common logical operators are AND (&&), OR(||), and NOT (!).
Logical operators are also binary operators.
Show Examples
Operator Description Example
Called Logical AND operator. If both the operands are non-zero, then the (A && B)
&&
condition becomes true. is false.
Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
! operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.
Bitwise Operators
The most common bitwise operators are AND (&), OR (|), XOR (^), NOT
(~), left shift (<<), and right shift (>>). Here the "~" operator is a unary
operator, while most of the other bitwise operators are binary in narure.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
------------------------
~A = 1100 0011
Show Examples
(A & B) =
Binary AND Operator copies a bit to the result if it exists in both 12, i.e.,
&
operands. 0000
1100
(A | B) =
61, i.e.,
| Binary OR Operator copies a bit if it exists in either operand.
0011
1101
(A ^ B) =
Binary XOR Operator copies the bit if it is set in one operand but not 49, i.e.,
^
both. 0011
0001
(~A ) =
Binary One's Complement Operator is unary and has the effect of ~(60),
~
'flipping' bits. i.e,. -
0111101
A << 2 =
Binary Left Shift Operator. The left operands value is moved left by the 240 i.e.,
<<
number of bits specified by the right operand. 1111
0000
A >> 2 =
Binary Right Shift Operator. The left operands value is moved right by the 15 i.e.,
>>
number of bits specified by the right operand. 0000
1111
Assignment Operators
Show Examples
C=A+B
will assign
Simple assignment operator. Assigns values from right side operands to
= the value
left side operand
of A + B to
C
C += A is
Add AND assignment operator. It adds the right operand to the left equivalent
+=
operand and assign the result to the left operand. to C = C +
A
C -= A is
Subtract AND assignment operator. It subtracts the right operand from equivalent
-=
the left operand and assigns the result to the left operand. to C = C -
A
C *= A is
Multiply AND assignment operator. It multiplies the right operand with equivalent
*=
the left operand and assigns the result to the left operand. to C = C *
A
Divide AND assignment operator. It divides the left operand with the C /= A is
/=
right operand and assigns the result to the left operand. equivalent
to C = C /
A
C %= A is
Modulus AND assignment operator. It takes modulus using two equivalent
%=
operands and assigns the result to the left operand. to C = C %
A
C <<= 2 is
<<= Left shift AND assignment operator. same as C
= C << 2
C >>= 2 is
>>= Right shift AND assignment operator. same as C
= C >> 2
C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2
C ^= 2 is
^= Bitwise exclusive OR and assignment operator. same as C
=C^2
C |= 2 is
|= Bitwise inclusive OR and assignment operator. same as C
=C|2
Hence, the expression "a = 5" assigns 5 to the variable "a", but "5 = a" is
an invalid expression in C.
The "=" operator, combined with the other arithmetic, relational and
bitwise operators form augmented assignment operators. For example,
the += operator is used as add and assign operator. The most common
assignment operators are =, +=, -=, *=, /=, %=, &=, |=, and ^=.
Besides the operators discussed above, there are a few other important
operators including sizeof and ? : supported by the C Language.
Show Examples
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
Operators Precedence in C
Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators will be evaluated first.
Show Examples
Other Operators in C
Apart from the above, there are a few other operators in C that are not
classified into any of the above categories. For example, the increment
and decrement operators (++ and --) are unary in nature and can appear
as a prefix or postfix to the operand.
The operators that work with the address of memory location such as the
address-of operator (&) and the dereference operator (*). The sizeof
operator (sizeof) appears to be a keyword but really an operator.
C also has the type cast operator (()) that forces the type of an operand
to be changed. C also uses the dot (.) and the arrow (->) symbols as
operators when dealing with derived data types such as struct and union.
Arithmetic Operators in C
Arithmetic operators in C are certain special symbols, predefined to
perform arithmetic operations. We are familiar with the basic arithmetic
operations − addition, subtraction, multiplication and division. C is a
computational language, so these operators are essential in performing a
computerised process.
Operator Description
#include <stdio.h>
int main(){
return 0;
}
Output
When you run this code, it will produce the following output −
Operand1: 10 Operand2: 3
Type Casting in C
The first three results are as expected, but the result of division is not.
You expect 10/3 to be a fractional number (3.333333). Is it because we
used the %d format specifier to print the outcome of the division? If we
change the last line of the code as follows −
printf("Division of op1 by op2: %f\n", op1/op2);
Now, change the last printf statement of the given program as follows −
When you run run the code again after making this change, it will show
the correct division −
Example
The result of arithmetic operations with at least one float (or double)
operand is always float. Take a look at the following example −
#include <stdio.h>
int main(){
return 0;
}
Output
Example
The following example shows how you can perform arithmetic operations
with two operands out of which one is a "char" type −
#include <stdio.h>
int main(){
return 0;
}
Output
operand1: F operand2: 3
Addition of op1 and op2: 73
Subtraction of op2 from op1: 67
Multiplication of op1 and op2: 210
Division of op1 by op2: 23
Since a char data type is a subset of int, the %c format specifier returns
the ASCII character associated with an integer returned by
the %d specifier.
Modulo Operator in C
Example
Take a look at the following example −
#include <stdio.h>
int main(){
return 0;
}
Output
Operand1: 10 Operand2: 3
Modulo of op1 and op2: 1
The modulo operator needs both the operands of int type. If not, the
compiler gives a type mismatch error. For example, change the data type of
"op1" to float in the above code and run the program again −
float op1 = 10;
int op2 = 3;
printf("Modulo of op1 and op2: %d\n", op1%op2);
Now, you will get a type mismatch error with the following message −
Negation Operator in C
Example
The following example highlights how you can use the negation operator
in C −
#include <stdio.h>
int main(){
int op1 = 5;
int op2 = -op1;
return 0;
}
Output
When you run this code, it will produce the following output −
Operand1: 5 Operand2: -5
In the above example, the "" symbol returns the negative value of op1
and assigns the same to op2.
Unary Operators in C
While most of the operators in C are binary in nature, there are a few
unary operators as well. An operator is said to be unary if it takes just a
single operand, unlike a binary operator which needs two operands.
The increment operator (++) adds 1 to the value of its operand variable
and assigns it back to the variable.
The statement a++ is equivalent to writing "a = a + 1." The "++" operator
can appear before or after the operand and it will have the same effect.
Hence, a++ is equivalent to ++a.
In the former case, "a" is assigned to "b" before the incrementation; while
in the latter case, the incrementation is performed before the assignment.
The decrement operator (--) subtracts 1 from the value of its operand
variable and assigns it back to the variable.
The "--" operator can appear before or after the operand and in either
case, it will have the same effect. Hence, "a--" is equivalent to "--a".
The "+" and "" operators are well known as binary addition and
subtraction operators. However, they can also be used in unary fashion.
When used as unary, they are prefixed to the operand variable.
Example
Take a look at the following example −
#include <stdio.h>
int main(){
char x = 'A';
char y = +x;
float a = 1.55;
float b = +a;
return 0;
}
Output
When you run this code, it will produce the following output −
x: A y: A
a: 1.550000 y: 1.550000
The Unary "−" Operator in C
The "−" symbol, that normally represents the subtraction operator, also
acts the unary negation operator in C. The following code shows how you
can use the unary negation operator in C.
Example
In this code, the unary negation operator returns the negative value of
"x" and assigns the same to another variable "y".
#include <stdio.h>
int main(){
int x = 5;
int y = -x;
return 0;
}
Output
x: 5 y: -5
We use the & symbol in C as the binary AND operator. However, we also
use the same & symbol in unary manner as the "address-of" operator.
Example
The & operator returns the memory address of its variable operand. Take
a look at the following example −
#include <stdio.h>
int main(){
char x = 'A';
printf ("Address of x: %d\n", &x);
return 0;
}
Output
Address of x: 6422047
char x = 'A';
printf ("Address of x: %p\n", &x);
Address of x: 000000000061FE1F
int x = 10;
int *y = &x;
When you want to store the memory address of a variable, the variable
should be declared with an asterisk (*) prefixed to it.
int x = 10;
int *y = &x;
Here the variable "y" stores the address of "x", hence "y" acts as a
pointer to "x". To access the value of "x" with the help of its pointer, use
the dereference operator (*).
Example 1
Take a look at the following example −
#include <stdio.h>
int main(){
int x = 10;
int *y = &x;
return 0;
}
Output
x: 10 Address of x: 6422036
Value at x with Dereference: 10
Example 2
You can also assign a value to the original variable with the help of the
dereference pointer −
#include <stdio.h>
int main(){
int x = 10;
int *y = &x;
return 0;
}
Output
x: 10 Address of x: 6422036
x: 20 with dereference: 20
The logical NOT operator (!) in C negates the value of a Boolean operand.
True becomes False and False becomes True. The logical NOT operator (!)
is a unary operator.
Example 1
The following example shows the usage of logical operators in C −
#include <stdio.h>
int main(){
int a = 0;
int b = 20;
return 0;
}
Output
Line 1 - Condition is true
Example 2
The following C code employs the NOT operator in a while loop −
#include <stdio.h>
int main(){
int i = 0;
return 0;
}
Output
In this code, the while loop continues to iterate till the expression "!(i >
5)" becomes False, which will be when the value of "i" becomes more
than 5.
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
0 1
1 0
Assuming that the int variable "a" has the value 60 (equivalent to 0011
1100 in binary), the "~a" operation results in -61 in 2s complement form,
as per the bitwise right-shift of its corresponding bits.
Example
Take a look at this example code −
#include <stdio.h>
int main(){
return 0;
}
Output
When you run this code, it will produce the following output −
Value of c is -61
Relational Operators in C
Relational operators in C are defined to perform comparison of two
values. The familiar angular brackets < and > are the relational operators
in addition to a few more as listed in the table below.
Example 1
#include <stdio.h>
int main(){
int op1 = 5;
int op2 = 3;
printf("op1: %d op2: %d op1 < op2: %d\n", op1, op2, op1 < op2);
return 0;
}
Output
Run the code and check its output −
Checks if the values of two operands are equal or not. If yes, then the
== (A == B)
condition becomes true.
Checks if the values of two operands are equal or not. If the values are
!= (A != B)
not equal, then the condition becomes true.
Checks if the value of left operand is greater than the value of right
> (A > B)
operand. If yes, then the condition becomes true.
Checks if the value of left operand is less than the value of right operand.
< (A < B)
If yes, then the condition becomes true.
Checks if the value of left operand is greater than or equal to the value of
>= (A >= B)
right operand. If yes, then the condition becomes true.
Checks if the value of left operand is less than or equal to the value of
<= (A <= B)
right operand. If yes, then the condition becomes true.
All the relational operators are binary operators. Since they perform
comparison, they need two operands on either side.
We use the = symbol in C as the assignment operator. So, C uses the "=="
(double equal) as the equality operator.
The angular brackets > and < are used as the "greater than" and "less
than" operators. When combined with the "=" symbol, they form the
">=" operator for "greater than or equal" and "<=" operator for "less
than or equal" comparison.
Finally, the "=" symbol prefixed with "!" (!=) is used as the inequality
operator.
Example 2
#include <stdio.h>
int main(){
int a = 21;
int b = 10;
int c ;
if(a == b){
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}
if (a < b){
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}
if (a > b){
printf("Line 3 - a is greater than b\n" );
} else {
printf("Line 3 - a is not greater than b \n\n" );
}
if (a <= b){
printf("Line 4 - a is either less than or equal to b\n" );
}
if (b >= a){
printf("Line 5 - b is either greater than or equal to b\n" );
}
if(a != b){
printf("Line 6 - a is not equal to b\n" );
} else {
printf("Line 6 - a is equal to b\n" );
}
return 0;
}
Output
When you run this code, it will produce the following output −
a: 21 b: 10
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
a: 5 b: 20
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Line 6 - a is not equal to b
Example 3
The == operator needs to be used with care. Remember that "=" is the
assignment operator in C. If used by mistake in place of the equality
operator, you get an incorrect output as follows −
#include <stdio.h>
int main(){
int a = 5;
int b = 3;
if (a = b){
printf("a is equal to b");
}
else {
printf("a is not equal to b");
}
return 0;
}
Output
The value of "b" is assigned to "a" which is non-zero, and hence
the if expression returns true.
a is equal to b
Example 4
We can have "char" types too as the operand for all the relational
operators, as the "char" type is a subset of "int" type. Take a look at this
example −
#include <stdio.h>
int main(){
char a = 'B';
char b = 'd';
if(a == b){
printf("Line 1 - a is equal to b \n");
} else {
printf("Line 1 - a is not equal to b \n");
}
if (a < b){
printf("Line 2 - a is less than b \n");
} else {
printf("Line 2 - a is not less than b \n");
}
if (a > b) {
printf("Line 3 - a is greater than b \n");
} else {
printf("Line 3 - a is not greater than b \n");
}
if(a != b) {
printf("Line 4 - a is not equal to b \n");
} else {
printf("Line 4 - a is equal to b \n");
}
return 0;
}
Output
Run the code and check its output −
a: B b: d
Line 1 - a is not equal to b
Line 2 - a is less than b
Line 3 - a is not greater than b
Line 4 - a is not equal to b
Logical Operators in C
Logical operators in C evaluate to either True or False. Logical operators
are typically used with Boolean operands.
The logical AND operator (&&) and the logical OR operator (||) are both
binary in nature (require two operands). The logical NOT operator (!) is a
unary operator.
Since C treats "0" as False and any non-zero number as True, any
operand to a logical operand is converted to a Boolean data.
Called Logical AND operator. If both the operands are non-zero, then the
&& (A && B)
condition becomes true.
Called Logical NOT Operator. It is used to reverse the logical state of its
! operand. If a condition is true, then Logical NOT operator will make it !(A)
false.
The && operator in C acts as the logical AND operator. It has the following
truth table −
a b a&&b
The above truth table shows that the result of && is True only if both the
operands are True.
Logical OR (||) Operator
C uses the double pipe symbol (||) as the logical OR operator. It has the
following truth table −
a b a||b
The above truth table shows that the result of || operator is True when
either of the operands is True, and False if both operands are false.
The logical NOT ! operator negates the value of a Boolean operand. True
becomes False, and False becomes True. Here is its truth table −
A !a
True False
False True
Unlike the other two logical operators && and ||, the logical NOT
operator ! is a unary operator.
Example 1
The following example shows the usage of logical operators in C −
#include <stdio.h>
int main(){
int a = 5;
int b = 20;
if (a && b){
printf("Line 1 - Condition is true\n" );
}
if (a || b){
printf("Line 2 - Condition is true\n" );
}
if (a && b){
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}
return 0;
}
Output
Example 2
In C, a char type is a subset of int type. Hence, logical operators can work
with char type too.
#include <stdio.h>
int main(){
char a = 'a';
char b = '\0'; // Null character
if (a && b){
printf("Line 1 - Condition is true\n" );
}
if (a || b){
printf("Line 2 - Condition is true\n" );
}
return 0;
}
Output
Example 3
The following example shows a compound Boolean expression in a C
program −
#include <stdio.h>
int main(){
return 0;
}
Output
Result:Pass
Example 4
The similar logic can also be expressed using the && operator as follows
−
#include <stdio.h>
int main(){
return 0;
}
Output
Result: Pass
Example 5
The following C code employs the NOT operator in a while loop −
#include <stdio.h>
int main(){
int i = 0;
return 0;
}
Output
In the above code, the while loop continues to iterate till the expression
"!(i > 5)" becomes false, which will be when the value of "i" becomes
more than 5.
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
Bitwise Operators in C
Bitwise operators in C allow low-level manipulation of data stored in
computers memory.
Additionally, the symbols ^ (XOR), << (left shift) and >> (right shift) are
the other bitwise operators.
Operator Description
& Binary AND Operator copies a bit to the result if it exists in both operands.
^ Binary XOR Operator copies the bit if it is set in one operand but not both.
~ Binary One's Complement Operator is unary and has the effect of 'flipping' bits.
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the
<<
right operand.
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by th
>>
right operand.
Even though these operators work on individual bits, they need the
operands in the form C data types or variables only, as a variable
occupies a specific number of bytes in the memory.
The bitwise AND (&) operator performs as per the following truth table −
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise binary AND performs logical operation on the bits in each position
of a number in its binary form.
Assuming that the two int variables "a" and "b" have the values 60
(equivalent to 0011 1100 in binary) and 13 (equivalent to 0000 1101 in
binary), the "a & b" operation results in 13, as per the bitwise ANDing of
their corresponding bits illustrated below −
0011 1100
& 0000 1101
---------
= 0000 1100
Advertisement
The bitwise OR (|) operator performs as per the following truth table −
0 0 0
0 1 1
1 0 1
1 1 1
Assuming that the two int variables "a" and "b" have the values 60
(equivalent to 0011 1100 in binary) and 13 (equivalent to 0000 1101 in
binary), then "a | b" results in 61, as per the bitwise OR of their
corresponding bits illustrated below −
0011 1100
| 0000 1101
---------
= 0011 1101
The binary number 00111101 corresponds to 61 in decimal.
The bitwise XOR (^) operator performs as per the following truth table −
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise binary XOR performs logical operation on the bits in each position
of a number in its binary form. The XOR operation is called "exclusive
OR".
Note: The result of XOR is 1 if and only if one of the operands is 1. Unlike
OR, if both bits are 1, XOR results in 0.
Assuming that the two int variables "a" and "b" have the values 60
(equivalent to 0011 1100 in binary) and 13 (equivalent to 0000 1101 in
binary), the "a ^ b" operation results in 49, as per the bitwise XOR of their
corresponding bits illustrated below −
0011 1100
^ 0000 1101
---------
= 0011 0001
The left shift operator is represented by the << symbol. It shifts each bit
in its left-hand operand to the left by the number of positions indicated by
the right-hand operand. Any blank spaces generated while shifting are
filled up by zeroes.
Assuming that the int variable "a" has the value 60 (equivalent to 0011
1100 in binary), the "a << 2" operation results in 240, as per the bitwise
left-shift of its corresponding bits illustrated below −
The right shift operator is represented by the >> symbol. It shifts each bit
in its left-hand operand to the right by the number of positions indicated
by the right-hand operand. Any blank spaces generated while shifting are
filled up by zeroes.
Assuming that the int variable a has the value 60 (equivalent to 0011
1100 in binary), the "a >> 2" operation results in 15, as per the bitwise
right-shift of its corresponding bits illustrated below −
a ~a
0 1
1 0
Assuming that the int variable "a" has the value 60 (equivalent to 0011
1100 in binary), then the "~a" operation results in -61 in 2s complement
form, as per the bitwise right-shift of its corresponding bits illustrated
below −
#include <stdio.h>
int main(){
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
return 0;
}
Output
When you run this code, it will produce the following output −
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Assignment Operators in C
In C language, the assignment operator stores a certain value in an
already declared variable. A variable in C can be assigned the value in the
form of a literal, another variable, or an expression.
C = A + B will assign
Simple assignment operator. Assigns values from right side
= the value of A + B to
operands to left side operand
C
C <<= 2 is same as C
<<= Left shift AND assignment operator.
= C << 2
C >>= 2 is same as C
>>= Right shift AND assignment operator.
= C >> 2
C &= 2 is same as C
&= Bitwise AND assignment operator.
=C&2
C ^= 2 is same as C =
^= Bitwise exclusive OR and assignment operator.
C^2
C |= 2 is same as C =
|= Bitwise inclusive OR and assignment operator.
C|2
You can declare a variable to be assigned a value later in the code, or you
can initialize it at the time of declaration.
On the other hand, the term rvalue refers to a data value that is stored at
some address in memory. A rvalue is an expression that cannot have a
value assigned to it which means an rvalue may appear on the right-hand
side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so they may not be assigned
and cannot appear on the left-hand side. Take a look at the following
valid and invalid statements −
Example 1
For example, the expression "a += b" has the same effect of performing
"a + b" first and then assigning the result back to the variable "a".
#include <stdio.h>
int main(){
int a = 10;
int b = 20;
a += b;
printf("a: %d", a);
return 0;
}
Output
a: 30
Example 2
Similarly, the expression "a <<= b" has the same effect of performing "a
<< b" first and then assigning the result back to the variable "a".
#include <stdio.h>
int main(){
int a = 60;
int b = 2;
a <<= b;
printf("a: %d", a);
return 0;
}
Output
a: 240
Example 3
Here is a C program that demonstrates the use of assignment operators
in C −
#include <stdio.h>
int main(){
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %%= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
return 0;
}
Output
When you compile and execute the above program, it will produce the
following result −
Line 1 - = Operator Example, Value of c = 21
Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2
The ++ and -- operators are unary and can be used as a prefix or posfix
to a variable.
Advertisement
#include <stdio.h>
int main() {
int a = 5, b = 5, c = 5, d = 5;
return 0;
}
Output
When you run this code, it will produce the following output −
a = 6
b = 6
c = 4
d = 4
Example Explanation
In other words, "a++" has the same effect as "++a", as both the
expressions increment the value of variable "a" by 1. Similarly, "a--" has
the same effect as "--a".
There are two types of increment operators – pre increment and post
increment.
Syntax
++variable_name;
Example
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + ++x ;
return 0;
}
When you run this code, it will produce the following output −
x = 11, y = 21
Syntax
variable_name++;
Example
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + x ++;
printf("x = %d, y = %d\n", x , y);
return 0;
}
When you run this code, it will produce the following output −
x = 11, y = 20
There are two types of decrement operators – pre decrement and post
decrement.
Syntax
--variable_name;
Example
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + --x;
return 0;
}
When you run this code, it will produce the following output −
x = 9, y = 19
Post (Postfix) Decrement Operator
In an expression, the post-decrement operator decreases the value of a
variable by 1 after the use of the value of the variable.
Syntax
variable_name--;
Example
#include <stdio.h>
int main() {
int x = 10;
int y = 10 + x --;
return 0;
}
When you run this code, it will produce the following output −
x = 9, y = 20
#include <stdio.h>
int main(){
a++;
printf("postfix increment a: %c\n", a);
++b;
printf("prefix increment b: %c\n", b);
x--;
printf("postfix decrement x : %d\n", x );
-- y;
printf("prefix decrement y : %d\n", y);
return 0;
}
Output
When you run this code, it will produce the following output −
a: a b: M
postfix increment a: b
prefix increment b: N
x: 5 y: 23
postfix decrement x: 4
prefix decrement y: 22
The above example shows that the prefix as well as postfix operators
have the same effect on the value of the operand variable. However,
when these "++" or "--" operators appear along with the other operators
in an expression, they behave differently.
Example 2
In the following code, the initial values of "a" and "b" variables are same,
but the printf() function displays different values −
#include <stdio.h>
int main(){
int x = 5, y = 5;
return 0;
}
Output
x: 5 y: 5
postfix increment x: 5
prefix increment y: 6
In the first case, the printf() function prints the value of "x" and then
increments its value. In the second case, the increment operator is
executed first, the printf() function uses the incremented value for
printing.
Example 1
Take a look at the following example −
#include <stdio.h>
int main(){
int x = 5, z;
printf("x: %d \n", x );
z = x++;
printf("x: %d z: %d\n", x , z);
return 0;
}
Output
x: 5
x: 6 z: 5
Since "x++" increments the value of "x" to 6, you would expect "z" to be
6 as well. However, the result shows "z" as 5. This is because the
assignment operator has a higher precedence over postfix increment
operator. Hence, the existing value of "x" is assigned to "z", before
incrementing "x".
Example 2
Take a look at another example below −
#include <stdio.h>
int main(){
int x = 5, y = 5, z;
z = ++ y;
printf("y: %d z: %d\n", y ,z );
return 0;
}
Output
When you run this code, it will produce the following output −
y: 5
y: 6 z: 6
The result may be confusing, as the value of "y" as well as "z" is now 6.
The reason is that the prefix increment operator has a higher precedence
than the assignment operator. Hence, "y" is incremented first and then its
new value is assigned to "z".
The associativity of operators also plays an important part. For increment and
decrement operators, the associativity is from left to right. Hence, if there
are multiple increment or decrement operators in a single expression, the
leftmost operator will be executed first, moving rightward.
Example 3
In this example, the assignment expression contains both the prefix as
well as postfix operators.
#include <stdio.h>
int main(){
int x = 5, y = 5, z;
z = x++ + ++ y;
printf("x: %d y: %d z: %d\n", x , y,z );
return 0;
}
Output
x: 6 y:6 z: 11
In this example, the first operation to be done is "y++" ("y" becomes 6).
Secondly the "+" operator adds "x" (which is 5) and "y", the result
assigned to "z" as 11, and then "x++" increments "x" to 6.
Example
The looping body is executed for all the values of a variable between the
initial and the final values, incrementing it after each round.
#include <stdio.h>
int main(){
int x ;
return 0;
}
Output
When you run this code, it will produce the following output −
x: 1
x: 2
x: 3
x: 4
x: 5
Ternary Operator in C
The ternary operator (?:) in C is a type of conditional operator. The term
"ternary" implies that the operator has three operands. The ternary
operator is often used to put multiple conditional (if-else) statements in a
more compact manner.
The following C program uses the ternary operator to check if the value of
a variable is even or odd.
#include <stdio.h>
int main(){
int a = 10;
return 0;
}
Output
When you run this code, it will produce the following output −
10 is Even
Change the value of "a" to 15 and run the code again. Now you will get
the following output −
15 is Odd
Example 2
#include <stdio.h>
int main(){
int a = 10;
if (a % 2 == 0){
printf("%d is Even\n", a);
}
else{
printf("%d is Odd\n", a);
}
return 0;
}
Output
Run the code and check its output −
10 is Even
Example 3
The following program compares the two variables "a" and "b", and
assigns the one with the greater value to the variable "c".
#include <stdio.h>
int main(){
return 0;
}
Output
When you run this code, it will produce the following output −
a: 100 b: 20 c: 100
Example 4
#include <stdio.h>
int main(){
if (a >= b){
c = a;
}
else {
c = b;
}
printf ("a: %d b: %d c: %d\n", a, b, c);
return 0;
}
Output
Run the code and check its output −
a: 100 b: 20 c: 100
Example 5
If you need to put multiple statements in the true and/or false operand of
the ternary operator, you must separate them by commas, as shown
below −
#include <stdio.h>
int main(){
return 0;
}
Output
In this code, the greater number is assigned to "c", along with printing
the appropriate message.
a is larger a: 100 b: 20 c: 20
Example 6
#include <stdio.h>
int main(){
return 0;
}
Output
Run the code and check its output −
a is larger
a: 100 b: 20 c: 100
Just as we can use nested if-else statements, we can use the ternary
operator inside the True operand as well as the False operand.
If expr1 turns false, it may check if expr5 is true and return expr6 or
expr7.
Example 1
Let us develop a C program to determine whether a number is divisible by
2 and 3, or by 2 but not 3, or 3 but not 2, or neither by 2 and 3. We will
use nested condition operators for this purpose, as shown in the following
code −
#include <stdio.h>
int main(){
int a = 15;
printf("a: %d\n", a);
(a % 2 == 0) ? (
(a%3 == 0)? printf("divisible by 2 and 3") : printf("divisible by 2 but not 3"))
:(
(a%3 == 0)? printf("divisible by 3 but not 2") : printf("not divisible by 2, not divisible by
3")
);
return 0;
}
Output
a: 15
divisible by 3 but not 2
a: 16
divisible by 2 but not 3
a: 17
not divisible by 2, not divisible by 3
a: 18
divisible by 2 and 3
Example 2
In this program, we have used nested ifelse statements for the same
purpose instead of conditional operators −
#include <stdio.h>
int main(){
int a = 15;
printf("a: %d\n", a);
if(a % 2 == 0){
if (a % 3 == 0){
printf("divisible by 2 and 3");
}
else {
printf("divisible by 2 but not 3");
}
}
else{
if(a % 3 == 0){
printf("divisible by 3 but not 2");
}
else {
printf("not divisible by 2, not divisible by 3");
}
}
return 0;
}
Output
When you run this code, it will produce the following output −
a: 15
divisible by 3 but not 2
It can be applied to any data type, float type, or pointer type variables.
sizeof(type or var);
When sizeof() is used with a data type, it simply returns the amount of
memory allocated to that data type. The outputs can be different on
different machines, for example, a 32-bit system can show a different
output as compared to a 64-bit system.
Example 1: Using the sizeof Operator in C
Take a look at the following example. It highlights how you can use the
sizeof operator in a C program −
#include <stdio.h>
int main(){
int a = 16;
return 0;
}
Output
On running this code, you will get the following output −
Size of variable a: 4
Size of int data type: 4
Size of char data type: 1
Size of float data type: 4
Size of double data type: 8
Example 2: Using sizeof with Struct
In this example, we declare a struct type and find the size of the struct
type variable.
#include <stdio.h>
struct employee {
char name[10];
int age;
double percent;
};
int main(){
struct employee e1 = {"Raghav", 25, 78.90};
printf("Size of employee variable: %d\n",sizeof(e1));
return 0;
}
Output
Run the code and check its output −
#include <stdio.h>
int main(){
Output
Run the code and check its output −
Size of arr: 40
We first find the size of the array and then divide it by the size of its data
type.
#include <stdio.h>
int main(){
Output
When you run this code, it will produce the following output −
No of elements in arr: 10
When the sizeof() is used with an expression, it returns the size of the
expression. Here is an example.
#include <stdio.h>
int main(){
char a = 'S';
double b = 4.65;
int s = (int)(a+b);
printf("Size of explicitly converted expression: %d\n",sizeof(s));
return 0;
}
Output
Run the code and check its output −
Size of variable a: 1
Size of an expression: 8
Size of explicitly converted expression: 4
The sizeof() operator returns the same value irrespective of the type. This
includes the pointer of a built−in type, a derived type, or a double
pointer.
#include <stdio.h>
int main(){
Operator Precedence in C
A single expression in C may have multiple operators of different types.
The C compiler evaluates its value based on the operator precedence and
associativity of operators.
x = 7 + 3 * 2;
Here, the multiplication operator "*" has a higher precedence than the
addition operator "+". So, the multiplication 3*2 is performed first and
then adds into 7, resulting in "x = 13".
Operator Associativity
15 / 5 * 2
Both the "/" (division) and "*" (multiplication) operators have the same
precedence, so the order of evaluation will be decided by associativity.
As per the above table, the associativity of the multiplicative operators is
from Left to Right. So, the expression is evaluated as −
(15 / 5) * 2
It evaluates to −
3*2=6
Example 1
In the following code, the multiplication and division operators have
higher precedence than the addition operator.
#include <stdio.h>
int main(){
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = a + b * c / d;
printf("e : %d\n" , e );
return 0;
}
Output
When you run this code, it will produce the following output −
e: 50
Example 2
We can use parenthesis to change the order of evaluation. Parenthesis ()
got the highest priority among all the C operators.
#include <stdio.h>
int main(){
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d;
printf("e: %d\n", e);
return 0;
}
Output
e: 90
Example 3
In the expression that calculates e, we have placed a+b in one
parenthesis, and c/d in another, multiplying the result of the two.
#include <stdio.h>
int main(){
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * (c / d);
printf("e: %d\n", e );
return 0;
}
Output
e: 90
The "++" and "− −" operators act as increment and decrement operators,
respectively. They are unary in nature and can be used as a prefix or
postfix to a variable.
Example
The following example shows how you can use the increment and
decrement operators in a C program −
#include <stdio.h>
int main(){
int x = 5, y = 5, z;
printf("x: %d \n", x);
z = x++;
printf("Postfix increment: x: %d z: %d\n", x, z);
z = ++y;
printf("Prefix increment. y: %d z: %d\n", y ,z);
return 0;
}
Output
x: 5
Postfix increment: x: 6 z: 5
Prefix increment. y: 6 z: 6
Here the second operand "y > 50" is evaluated only if the first expression
evaluates to True.
C - Misc Operators
Besides the main categories of operators (arithmetic, logical, assignment,
etc.), C uses the following operators that are equally important. Let us
discuss the operators classified under this category.
The "&" symbol, already defined in C as the Binary AND Operator copies a
bit to the result if it exists in both operands. The "&" symbol is also
defined as the address−of operator.
sizeof(type or var);
When sizeof() is used with the data types, it simply returns the amount of
memory allocated to that data type. The output can be different on
different machines like a 32−bit system can show different output while a
64−bit system can show different of the same data types.
Example
Here is an example in C language
#include <stdio.h>
int main(){
int a = 16;
return 0;
}
Output
When you run this code, it will produce the following output −
Size of variable a: 4
Size of int data type: 4
Size of char data type: 1
Size of float data type: 4
Size of double data type: 8
Address-of Operator in C
int a;
Assuming that the compiler creates the variable at the address 1000 and
"x" at the address 2000, then the address of "a" is stored in "x".
Example
Let us understand this with the help of an example. Here, we have
declared an int variable. Then, we print its value and address −
#include <stdio.h>
int main(){
return 0;
}
Output
The name of the variable must be prefixed with an asterisk (*). The data
type indicates it can store the address of which data type. For example −
int *x;
float *y;
The "y" variable is a pointer that stores the memory location of a float
variable.
int a;
int *x = &a;
We can see that the address of this variable (any type of variable for that
matter) is an integer. So, if we try to store it in a pointer variable of int
type, see what happens −
The compiler doesnt accept this, and reports the following error −
initialization of 'int *' from incompatible pointer type 'float *' [-Wincompatible-pointer-
types]
It indicates that the type of a variable and the type of its pointer must be
the same.
In C, variables have specific data types that define their size and how
they store values. Declaring a pointer with a matching type (e.g., "float
*") enforces type compatibility between the pointer and the data it points
to.
Example 1
Take a look at the following example −
#include <stdio.h>
int main(){
return 0;
}
Output
var1: 10.550000
address of var1: 6422044
floatptr: 6422044
address of floatptr: 6422032
Example 2
The * operator is called the Dereference operator. It returns the value
stored in the address which is stored in the pointer, i.e., the value of the
variable it is pointing to. Take a look at the following example −
#include <stdio.h>
int main(){
return 0;
}
Output
The term "ternary" implies that the operator has three operands. The
ternary operator is often used to put conditional (if−else) statements in a
compact way.
Example
The following C program uses the ? operator to check if the value of a is
even or odd.
#include <stdio.h>
int main(){
int a = 10;
(a % 2==0) ? printf("%d is Even\n", a) : printf("%d is Odd\n", a);
return 0;
}
Output
10 is Even
Change the value of "a" to 15 and run the code again. Now you will get
the following output −
15 is Odd
In C language, you can define a derived data type with struct and union
keywords. A derived or user−defined data type that groups together
member elements of different types.
The dot operator is a member selection operator, when used with the struct or
union variable. The dot (.) operator has the highest operator precedence in
C Language and its associativity is from left to right.
var.member;
struct newtype {
type elem1;
type elem2;
type elem3;
...
...
};
var.elem1;
Example
Let us declare a struct type named book, declare a struct variable. The
following example shows the use of "." operator to access the members in
the book structure.
#include <stdio.h>
struct book{
char title[10];
double price;
int pages;
};
int main(){
return 0;
}
Output
Title: Learn C
Price: 675.500000
No of Pages: 325
size of book struct: 32
The Indirection Operator in C
struct type {
type var1;
type var2;
type var3;
...
...
};
struct book {
char title[10];
double price;
int pages;
};
You can also store the address of a struct variable in the struct pointer
variable.
struct book *strptr;
strptr = &b1;
Example
In this example, strptr is a pointer to struct book b1 variable. Hence,
strrptr−>title returns the title, similar to b1.title does.
#include <stdio.h>
#include <string.h>
struct book {
char title[10];
double price;
int pages;
};
int main() {
struct book b1 = {"Learn C", 675.50, 325};
struct book *strptr;
strptr = &b1;
printf("Title: %s\n", strptr->title);
printf("Price: %lf\n", strptr->price);
printf("No of Pages: %d\n", strptr->pages);
return 0;
}
Output
Title: Learn C
Price: 675.500000
No of Pages: 325