0% found this document useful (0 votes)
9 views83 pages

Operators

The document provides an overview of operators in the C programming language, categorizing them into unary, binary, and ternary types, along with specific examples of arithmetic, relational, logical, bitwise, assignment, and miscellaneous operators. It explains how these operators function and their precedence in expressions, emphasizing the importance of understanding operator behavior for effective programming. Additionally, the document includes examples and code snippets to illustrate the use of various operators in C.

Uploaded by

adityaprasad6671
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)
9 views83 pages

Operators

The document provides an overview of operators in the C programming language, categorizing them into unary, binary, and ternary types, along with specific examples of arithmetic, relational, logical, bitwise, assignment, and miscellaneous operators. It explains how these operators function and their precedence in expressions, emphasizing the importance of understanding operator behavior for effective programming. Additionally, the document includes examples and code snippets to illustrate the use of various operators in C.

Uploaded by

adityaprasad6671
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

C - Operators

An operator is a symbol that tells the compiler to perform specific


mathematical or logical functions. By definition, an operator performs a
certain operation on operands. An operator needs one or more operands
for the operation to be performed.

Depending on how many operands are required to perform the operation,


operands are called as unary, binary or ternary operators. They need one,
two or three operands respectively.

 Unary operators − ++ (increment), -- (decrement), ! (NOT), ~ (compliment),


& (address of), * (dereference)
 Binary operators − arithmetic, logical and relational operators except !
 Ternary operators − The ? operator

C language is rich in built-in operators and provides the following types of


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 (/).

In addition, the modulo (%) is an important arithmetic operator that


computes the remainder of a division operation. Arithmetic operators are
used in forming an arithmetic expression. These operators are binary in
nature in the sense they need two operands, and they operate on numeric
operands, which may be numeric literals, variables or expressions.

For example, take a look at this simple expression −


a+b

Here "+" is an arithmetic operator. We shall learn more about arithmetic


operators in C in a subsequent chapter.

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

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

Modulus Operator and remainder of after an


% B%A=0
integer division.

Increment operator increases the integer value by


++ A++ = 11
one.

Decrement operator decreases the integer value by


-- A-- = 9
one.

Advertisement

Relational Operators

We are also acquainted with relational operators while learning secondary


mathematics. These operators are used to compare two operands and
return a boolean value (true or false). They are used in a boolean
expression.

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.

For example, in the Boolean expression −


a>b

Here, ">" is a relational operator.

We shall learn more about with relational operators and their usage in one
of the following chapters.

Show Examples

Operator Description Example

(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

These operators are used to combine two or more boolean expressions.


We can form a compound Boolean expression by combining Boolean
expression with these operators. An example of logical operator is as
follows −

a >= 50 && b >= 50

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 OR Operator. If any of the two operands is non-zero, then (A || B)


||
the condition becomes true. is true.

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.

We will discuss more about Logical Operators in C in a subsequent


chapter.

Bitwise Operators

Bitwise operators let you manipulate data stored in computers memory.


These operators are used to perform bit-level operations on operands.

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.

Bitwise operator works on bits and perform bit−by−bit operation. The


truth tables for &, "|", and "^" are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100
B = 0000 1101

------------------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C. Assume


variable 'A' holds 60 and variable 'B' holds 13, then −

Show Examples

Operator Description Example

(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

As the name suggests, an assignment operator "assigns" or sets a value


to a named variable in C. These operators are used to assign values to
variables. The "=" symbol is defined as assignment operator in C,
however it is not to be confused with its usage in mathematics.

The following table lists the assignment operators supported by the C


language −

Show Examples

Operator Description Example

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 ^=.

Misc Operators &map; sizeof & ternary

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.

&a; returns the actual address of the


& Returns the address of a variable.
variable.

* Pointer to a variable. *a;

If Condition is true ? then value X :


?: Conditional Expression.
otherwise value Y

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression


and decides how an expression is evaluated. Certain operators have
higher precedence than others; for example, the multiplication operator
has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because


operator * has a higher precedence than +, so it first gets multiplied with
3*2 and then adds into 7.

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

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right


Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

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.

The C99 version of C introduced a few additional operators such as auto,


decltype.

A single expression in C may have multiple operators of different type.


The C compiler evaluates its value based on the operator precedence and
associativity of operators. For example, in the following expression −
a+b*c

The multiplication operand takes precedence over the addition operator.

We shall understand these properties with examples in a subsequent


chapter.

Many other programming languages, which are called C-family languages


(such as C++, C#, Java, Perl and PHP) have an operator nomenclature
that is similar to C.

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.

In addition to the above operations assigned to the four symbols +, −, *,


and / respectively, C has another arithmetic operator called the modulo
operator for which we use the %symbol.

The following table lists the arithmetic operators in C −

Operator Description

+ Adds two operands.

Subtracts second operand from the first.

* Multiplies both operands.

/ Divides numerator by denominator.

% Modulus Operator and remainder of after an integer division.

++ Increment operator increases the integer value by one.

-- Decrement operator decreases the integer value by one.


The ++ and -- operators are also listed in the above table. We shall learn
about increment and decrement operators in a separate chapter.

Example: Arithmetic Operators in C

The following example demonstrates how to use these arithmetic


operators in a C program −

#include <stdio.h>

int main(){

int op1 = 10;


int op2 = 3;

printf("Operand1: %d Operand2: %d \n\n", op1, op2);


printf("Addition of op1 and op2: %d\n", op1 + op2);
printf("Subtraction of op2 from op1: %d\n", op1 - op2);
printf("Multiplication of op1 and op2: %d\n", op1 * op2);
printf("Division of op1 by op2: %d\n", op1/op2);

return 0;
}

Output
When you run this code, it will produce the following output −

Operand1: 10 Operand2: 3

Addition of op1 and op2: 13


Subtraction of op2 from op1: 7
Multiplication of op1 and op2: 30
Division of op1 by op2: 3
Advertisement

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 the outcome of the division operation will be "0.000000", which is


even more surprising. The reason why C behaves like this is because the
division of an integer with another integer always returns an integer.

To obtain floating-point division, at least one operand must be a float, or


you need to use the typecast operator to change one of the integer
operands to float.

Now, change the last printf statement of the given program as follows −

printf("Division of op1 by op2: %f\n", (float)op1/op2);

When you run run the code again after making this change, it will show
the correct division −

Division of op1 by op2: 3.333333

Note: If you use %d format specifier for a floating-point expression, it will


always result in "0".

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(){

int op1 = 10;


float op2 = 2.5;

printf("Operand1: %d Operand2: %f\n", op1, op2);


printf("Addition of op1 and op2: %f\n", op1 + op2);
printf("Subtraction of op2 from op1: %f\n", op1 - op2);
printf("Multiplication of op1 and op2: %f\n", op1 * op2);
printf("Division of op1 by op2: %f\n", op1/op2);

return 0;
}
Output

Run the code and check its output −

Operand1: 10 Operand2: 2.500000


Addition of op1 and op2: 12.500000
Subtraction of op2 from op1: 7.500000
Multiplication of op1 and op2: 25.000000
Division of op1 by op2: 4.000000

Arithmetic Operations with char Data Type

In C, char data type is a subset of int type. Hence, we can perform


arithmetic operations with char operands.

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(){

char op1 = 'F';


int op2 = 3;

printf("operand1: %c operand2: %d\n", op1, op2);


printf("Addition of op1 and op2: %d\n", op1 + op2);
printf("Subtraction of op2 from op1: %d\n", op1 - op2);
printf("Multiplication of op1 and op2: %d\n", op1 * op2);
printf("Division of op1 by op2: %d\n", op1/op2);

return 0;
}
Output

Run the code and check its 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.

If any arithmetic operation between two char operands results in an


integer beyond the range of char, the %c specifier displays blank.

Modulo Operator in C

The modulo operator (%) returns the remainder of a division operation.

Example
Take a look at the following example −

#include <stdio.h>

int main(){

int op1 = 10;


int op2 = 3;

printf("Operand1: %d Operand2: %d\n", op1, op2);


printf("Modulo of op1 and op2: %d\n", op1%op2);

return 0;
}
Output

Run the code and check its 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 −

error: invalid operands to binary % (have 'float' and 'int')

It does allow char operands for modulo operations though.

Negation Operator in C

The increment and decrement operators represented by the


symbols ++ and -- are unary operators. They have been covered in a
separate chapter. The "−" symbol, representing subtraction operator, also
acts a unary negation operator.

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;

printf("Operand1: %d Operand2: %d\n", op1, op2);

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.

Some operators in C are binary as well as unary in their usage. Examples


of unary operators in C include ++, --, !, etc.

The Increment Operator in C

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.

However, when the increment operator appears along with other


operators in an expression, its effect is not the same. The precedence of
"prefix ++" is more than "postfix ++". Hence, "b = a++;" is not the same
as "b = ++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 in C

The decrement operator (--) subtracts 1 from 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 in either
case, it will have the same effect. Hence, "a--" is equivalent to "--a".

However, when the decrement operator appears along with other


operators in an expression, its effect is not the same. The precedence of
"prefix --" is more than "postfix --". Hence, "b = a--" is not the same as "b
= --a".
In the former case, "a" is assigned to "b" before the decrementation;
while in the latter case, the decrementation is performed before the
assignment.

The Unary "+" Operator in C

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.

The "+" operator is present implicitly whenever a positive value is


assigned to any numeric variable. The statement "int x = 5;" is same as "int
x = +5;". The same logic applies to float and char variable too.

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;

printf ("x: %c y: %c\n", x,y);


printf ("a: %f y: %f\n", a,b);

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;

printf("x: %d y: %d\n", x, y);

return 0;
}
Output

Run the code and check its output −

x: 5 y: -5

The Address-of Operator (&) in C

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

Run the code and check its output −

Address of x: 6422047

Note: The C compiler assigns a random memory address whenever a


variable is declared. Hence, the result may vary every time the address is
printed.

The format specifier %p is used to get a hexadecimal representation of


the memory address.

char x = 'A';
printf ("Address of x: %p\n", &x);

This prints the address of "x" in hexadecimal format −

Address of x: 000000000061FE1F

The address of a variable is usually stored in a "pointer variable". The


pointer variable is declared with a "*" prefix. In the code snippet below,
"x" is a normal integer variable while "y" is a pointer variable.

int x = 10;
int *y = &x;

The Dereference Operator (*) in C

We normally use the "*" symbol as the multiplication operator. However,


it is also used as the "dereference operator" in C.

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;

printf ("x: %d Address of x: %d\n", x, &x);


printf("Value at x with Dereference: %d", *y);

return 0;
}
Output

Run the code and check its 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;

printf("x: %d Address of x %d\n", x, &x);


*y = 20;

printf("x: %d with Dereference: %d", x, *y);

return 0;
}
Output

Run the code and check its output −

x: 10 Address of x: 6422036
x: 20 with dereference: 20

The Logical NOT Operator (!) in C

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;

if (!(a && b)){


printf("Line 1 - Condition is true\n" );
}

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;

while (!(i > 5)){


printf("i = %d\n", i);
i++;
}

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

The 1's Complement Operator (~) in C

The 1's complement operator (~) in C is a unary operator, needing just


one operand. It has the effect of "flipping" the bits, which means the 1's
are replaced by 0's and vice versa in the binary representation of any
number.
a ~a

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.

~ 0011 1100 = 1100 0011

The binary number "1100 0011" corresponds to -61 in decimal.

Example
Take a look at this example code −

#include <stdio.h>

int main(){

int a = 60; /* 60 = 0011 1100 */


int c = 0;

c = ~a; /* -61 = 1100 0011 */

printf("Value of c is %d \n", c);

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.

These relational operators are used in Boolean expressions. All the


relational operators evaluate to either True or False.

C doesnt have a Boolean data type. Instead, "0" is interpreted as False


and any non-zero value is treated as True.

Example 1

Here is a simple example of relational operator in C −

#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 −

op1: 5 op2: 3 op1 < op2: 0

Relational operators have an important role to play in decision-control and


looping statements in C.

The following table lists all the relational operators in C –


Operator Description Example

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

The following example shows all the relational operators in use.

#include <stdio.h>

int main(){

int a = 21;
int b = 10;
int c ;

printf("a: %d b: %d\n", a,b);

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" );
}

/* Lets change value of a and b */


a = 5;
b = 20;

printf("a: %d b: %d\n", a,b);

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';

printf("a: %c b: %c\n", a,b);

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

Relational operators cannot be used for comparing secondary types such


as arrays or derived types such as struct or union types.

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.

Here is a table showing the logical operators in C –


Operator Description Example

Called Logical AND operator. If both the operands are non-zero, then the
&& (A && B)
condition becomes true.

Called Logical OR Operator. If any of the two operands is non-zero, then


|| (A || B)
the 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 result of a logical operator follows the principle of Boolean algebra.


The logical operators follow the following truth tables.

Logical AND (&&) Operator

The && operator in C acts as the logical AND operator. It has the following
truth table −

a b a&&b

true true True

true false False

false true False

false false False

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

true true True

true false True

false true true

false false false

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.

Logical NOT (!) Operator

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" );
}

/* lets change the value of a and b */


a = 0;
b = 10;

if (a && b){
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}

if (!(a && b)){


printf("Line 4 - Condition is true\n" );
}

return 0;
}
Output

Run the code and check its output −

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

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

Run the code and check its output −

Line 2 - Condition is true

Logical operators are generally used to build a compound boolean


expression. Along with relational operators, logical operators too are used
in decision-control and looping statements in C.

Example 3
The following example shows a compound Boolean expression in a C
program −

#include <stdio.h>

int main(){

int phy = 50;


int maths = 60;

if (phy < 50 || maths < 50){


printf("Result:Fail");
}
else {
printf("Result:Pass");
}

return 0;
}
Output
Result:Pass

Example 4
The similar logic can also be expressed using the && operator as follows

#include <stdio.h>

int main(){

int phy = 50;


int maths = 60;

if (phy >= 50 && maths >= 50){


printf("Result: Pass");
}
else {
printf("Result: Fail");
}

return 0;
}
Output

Run the code and check its 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;

while (!(i > 5)){


printf("i = %d\n", i);
i++;
}

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

C has bitwise counterparts of the logical operators such as bitwise AND


(&), bitwise OR (|), and binary NOT or complement (~) operator.

Bitwise Operators in C
Bitwise operators in C allow low-level manipulation of data stored in
computers memory.

Bitwise operators contrast with logical operators in C. For example, the


logical AND operator (&&) performs AND operation on two Boolean
expressions, while the bitwise AND operator (&) performs the AND
operation on each corresponding bit of the two operands.
For the three logical operators &&, ||, and !, the corresponding bitwise
operators in C are &, | and ~.

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 OR Operator copies a bit if it exists in either operand.

^ 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.

Bitwise AND Operator (&) in C

The bitwise AND (&) operator performs as per the following truth table −

bit a bit b a&b

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

The binary number 00001100 corresponds to 12 in decimal.

Advertisement

Bitwise OR (|) Operator

The bitwise OR (|) operator performs as per the following truth table −

bit a bit b a|b

0 0 0

0 1 1

1 0 1

1 1 1

Bitwise binary OR 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), 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.

Bitwise XOR (^) Operator

The bitwise XOR (^) operator performs as per the following truth table −

bit a bit b a^b

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 binary number 00110001 corresponds to 49 in decimal.

The Left Shift (<<) Operator

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 −

0011 1100 << 2 = 1111 0000

The binary number 11110000 corresponds to 240 in decimal.

The Right Shift (>>) Operator

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 −

0011 1100 >> 2 = 0000 1111

The binary number 00001111 corresponds to 15 in decimal.

The 1's Complement (~) Operator

The 1's compliment operator (~) in C is a unary operator, needing just


one operand. It has the effect of "flipping" the bits, which means 1s are
replaced by 0s and vice versa.

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 −

~ 0011 1100 = 1100 0011

The binary number 1100 0011 corresponds to -61 in decimal.


Example
In this example, we have highlighted the operation of all the bitwise
operators:

#include <stdio.h>

int main(){

unsigned int a = 60; /* 60 = 0011 1100 */


unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


printf("Line 1 - Value of c is %d\n", c );

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 );

c = ~a; /*-61 = 1100 0011 */


printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */


printf("Line 5 - Value of c is %d\n", c );

c = a >> 2; /* 15 = 0000 1111 */


printf("Line 6 - 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.

The value to be assigned forms the right-hand operand, whereas the


variable to be assigned should be the operand to the left of the "="
symbol, which is defined as a simple assignment operator in C.

In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C


language −

Operator Description Example

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

Add AND assignment operator. It adds the right operand to C += A is equivalent


+=
the left operand and assign the result to the left operand. to C = C + A

Subtract AND assignment operator. It subtracts the right


C -= A is equivalent
-= operand from the left operand and assigns the result to the
to C = C - A
left operand.

Multiply AND assignment operator. It multiplies the right


C *= A is equivalent
*= operand with the left operand and assigns the result to the
to C = C * A
left operand.

Divide AND assignment operator. It divides the left operand


C /= A is equivalent
/= with the right operand and assigns the result to the left
to C = C / A
operand.
Modulus AND assignment operator. It takes modulus using C %= A is equivalent
%=
two operands and assigns the result to the left operand. to C = C % A

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

Simple Assignment Operator (=)

The = operator is one of the most frequently used operators in C. As per


the ANSI C standard, all the variables must be declared in the beginning.
Variable declaration after the first processing statement is not allowed.

You can declare a variable to be assigned a value later in the code, or you
can initialize it at the time of declaration.

You can use a literal, another variable, or an expression in the assignment


statement.

int x = 10; // declaration with initialization


int y; // declaration
y = 20; // assignment later
int z = x + y; // assign an expression
int d = 3, f = 5; // definition and initializing d and f.
char x = 'x'; // the variable x has the value 'x'.

Once a variable of a certain type is declared, it cannot be assigned a


value of any other type. In such a case the C compiler reports a type
mismatch error.
In C, the expressions that refer to a memory location are called "lvalue"
expressions. A lvalue may appear as either the left-hand or right-hand
side of an assignment.

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 −

int g = 20; // valid statement


10 = 20; // invalid statement
Advertisement

Augmented Assignment Operators

In addition to the = operator, C allows you to combine arithmetic and


bitwise operators with the = symbol to form augmented or compound
assignment operator. The augmented operators offer a convenient
shortcut for combining arithmetic or bitwise operation with assignment.

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

Run the code and check its 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

Run the code and check its 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

Increment and Decrement Operators in C

C - Increment and Decrement Operators

The increment operator (++) increments the value of a variable by 1,


while the decrement operator (--) decrements the value.

Increment and decrement operators are frequently used in the


construction of counted loops in C (with the for loop). They also have their
application in the traversal of array and pointer arithmetic.

The ++ and -- operators are unary and can be used as a prefix or posfix
to a variable.

Advertisement

Example of Increment and Decrement Operators

The following example contains multiple statements demonstrating the


use of increment and decrement operators with different variations −

#include <stdio.h>

int main() {
int a = 5, b = 5, c = 5, d = 5;

a++; // postfix increment


++b; // prefix increment
c--; // postfix decrement
--d; // prefix decrement

printf("a = %d\n", a);


printf("b = %d\n", b);
printf("c = %d\n", c);
printf("d = %d\n", d);

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".

The expression "a++;" can be treated as the equivalent of the statement


"a = a + 1;". Here, the expression on the right adds 1 to "a" and the
result is assigned back to 1, therby the value of "a" is incremented by 1.

Similarly, "b--;" is equivalent to "b = b 1;".

Types of Increment Operator

There are two types of increment operators – pre increment and post
increment.

Pre (Prefix) Increment Operator


In an expression, the pre-increment operator increases the value of a
variable by 1 before the use of the value of the variable.

Syntax
++variable_name;
Example

In the following example, we are using a pre-increment operator, where


the value of "x" will be increased by 1, and then the increased value will
be used in the expression.

#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 = 21

Post (Postfix) Increment Operator


In an expression, the post-increment operator increases the value of a
variable by 1 after the use of the value of the variable.

Syntax
variable_name++;
Example

In the following example, we are using post-increment operator, where


the value of "x" will be used in the expression and then it will be
increased by 1.

#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

Types of Decrement Operator

There are two types of decrement operators – pre decrement and post
decrement.

Pre (Prefix) decrement Operator


In an expression, the pre-decrement operator decreases the value of a
variable by 1 before the use of the value of the variable.

Syntax
--variable_name;

Example

In the following example, we are using a pre-decrement operator, where


the value of "x" will be decreased by 1, and then the decreased value will
be used in the expression.

#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 = 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

In the following example, we are using post-decrement operator, where


the value of "x" will be used in the expression and then it will be
decreased by 1.

#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 = 9, y = 20

More Examples of Increment and Decrement Operators


Example 1
The following example highlights the use of prefix/postfix
increment/decrement −

#include <stdio.h>

int main(){

char a = 'a', b = 'M';


int x = 5, y = 23;
printf("a: %c b: %c\n", a, b);

a++;
printf("postfix increment a: %c\n", a);

++b;
printf("prefix increment b: %c\n", b);

printf("x: %d y: %d\n", x , y);

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;

printf("x: %d y: %d\n", x , y);


printf("postfix increment x: %d\n", x ++);
printf("prefix increment y: %d\n", ++ y);

return 0;
}
Output

Run the code and check its 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.

Operator Precedence of Increment and Decrement Operators

There are a number of operators in C. When multiple operators are used


in an expression, they are executed as per their order of precedence.
Increment and decrement operators behave differently when used along
with other operators.

When an expression consists of increment or decrement operators


alongside other operators, the increment and decrement operations are
performed first. Postfix increment and decrement operators have higher
precedence than prefix increment and decrement operators.

Read also: Operator Precedence in C

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

Run the code and check its 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;

printf("x: %d y: %d\n", x , y);

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

Run the code and check its 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.

Using the Increment Operator in Loop

In C, the most commonly used syntax of a for loop is as follows −

for (init_val; final_val; increment) {


statement(s);
}

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 ;

for (x = 1; x <= 5; x++){


printf("x: %d\n", 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.

Syntax of Ternary Operator in C

The ternary operator is used with the following syntax −

exp1 ? exp2 : exp3

It uses three operands −

 exp1 − A Boolean expression evaluating to true or false


 exp2 − Returned by the ? operator when exp1 is true
 exp3 − Returned by the ? operator when exp1 is false
Advertisement

Example 1: Ternary Operator in C

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;

(a % 2 == 0) ? printf("%d is Even \n", a) : printf("%d is Odd \n", a);

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

The conditional operator is a compact representation of ifelse construct.


We can rewrite the logic of checking the odd/even number by the
following code −

#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(){

int a = 100, b = 20, c;


c = (a >= b) ? a : b;

printf ("a: %d b: %d c: %d\n", a, b, c);

return 0;
}

Output
When you run this code, it will produce the following output −

a: 100 b: 20 c: 100

Example 4

The corresponding code with ifelse construct is as follows −

#include <stdio.h>

int main(){

int a = 100, b = 20, c;

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(){

int a = 100, b = 20, c;

c = (a >= b) ? printf ("a is larger "), c = a : printf("b is larger "), c = b;

printf ("a: %d b: %d c: %d\n", a, b, c);

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

The corresponding program with the use of ifelse statements is as follows


#include <stdio.h>

int main(){

int a = 100, b = 20, c;

if(a >= b){


printf("a is larger \n");
c = a;
}
else{
printf("b is larger \n");
c = b;
}
printf ("a: %d b: %d c: %d\n", a, b, c);

return 0;
}

Output
Run the code and check its output −

a is larger
a: 100 b: 20 c: 100

Nested Ternary Operator

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.

exp1 ? (exp2 ? expr3 : expr4) : (exp5 ? expr6: expr7)

First C checks if expr1 is true. If so, it checks expr2. If it is true, the


result is expr3; if false, the result is expr4.

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

Check for different values −

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

C - The sizeof Operator


The sizeof operator is a compile−time unary operator. It is used to compute
the size of its operand, which may be a data type or a variable. It returns
the size in number of bytes.

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;

printf("Size of variable a: %d \n",sizeof(a));


printf("Size of int data type: %d \n",sizeof(int));
printf("Size of char data type: %d \n",sizeof(char));
printf("Size of float data type: %d \n",sizeof(float));
printf("Size of double data type: %d \n",sizeof(double));

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 −

Size of employee variable: 24

Example 3: Using sizeof with Array

In the following code, we have declared an array of 10 int values.


Applying the sizeof operator on the array variable returns 40. This is
because the size of an int is 4 bytes.

#include <stdio.h>

int main(){

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


printf("Size of arr: %d\n", sizeof(arr));
}

Output
Run the code and check its output −
Size of arr: 40

Example 4: Using sizeof to Find the Length of an Array

In C, we dont have a function that returns the number of elements in a


numeric array (we can get the number of characters in a string using
the strlen() function). For this purpose, we can use the sizeof() operator.

We first find the size of the array and then divide it by the size of its data
type.

#include <stdio.h>

int main(){

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


int y = sizeof(arr)/sizeof(int);

printf("No of elements in arr: %d\n", y);


}

Output
When you run this code, it will produce the following output −

No of elements in arr: 10

Example 5: Using sizeof in Dynamic Memory Allocation

The sizeof operator is used to compute the memory block to be


dynamically allocated with the malloc() and calloc() functions.

The malloc() function is used with the following syntax −

type *ptr = (type *) malloc(sizeof(type)*number);

The following statement allocates a block of 10 integers and stores its


address in the pointer −

int *ptr = (int *)malloc(sizeof(int)*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;

printf("Size of variable a: %d\n",sizeof(a));


printf("Size of an expression: %d\n",sizeof(a+b));

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

Example 6: The Size of a Pointer in C

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(){

printf("Size of int data type: %d \n", sizeof(int *));


printf("Size of char data type: %d \n", sizeof(char *));
printf("Size of float data type: %d \n", sizeof(float *));
printf("Size of double data type: %d \n", sizeof(double *));
printf("Size of double pointer type: %d \n", sizeof(int **));
}
Output
Run the code and check its output −

Size of int data type: 8


Size of char data type: 8
Size of float data type: 8
Size of double data type: 8
Size of double pointer type: 8

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.

The precedence of operators determines the order in which they are


evaluated in an expression. Operators with higher precedence are
evaluated first.

For example, take a look at this expression −

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".

The following table lists the order of precedence of operators in C. Here,


operators with the highest precedence appear at the top of the table, and
those with the lowest appear at the bottom.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Within an expression, higher precedence operators will be evaluated first.

Operator Associativity

In C, the associativity of operators refers to the direction (left to right or


right to left) an expression is evaluated within a program. Operator
associativity is used when two operators of the same precedence appear
in an expression.

In the following example −

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.

The left−to−right associativity of multiplicative operator results in


multiplication of "b" and "c" divided by "e". The result then adds up to the
value of "a".

#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

Run the code and check its output −

e: 90

In this expression, the addition of a and b in parenthesis is first. The


result is multiplied by c and then the division by d takes place.

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

On running this code, you will get the following output −

e: 90

Precedence of Post / Prefix Increment / Decrement Operators

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.

When used as a standalone, using these operators in a prefix or post−fix


manner has the same effect. In other words, "a++" has the same effect
as "++a". However, when these "++" or "− −" operators appear along
with other operators in an expression, they behave differently.

Postfix increment and decrement operators have higher precedence than


prefix increment and decrement operators.

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

Run the code and check its output −

x: 5
Postfix increment: x: 6 z: 5
Prefix increment. y: 6 z: 6

Logical operators have left−to−right associativity. However, the compiler


evaluates the least number of operands needed to determine the result of
the expression. As a result, some operands of the expression may not be
evaluated.

For example, take a look at the following expression −

x > 50 && y > 50

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.

The "*" symbol − A well−known arithmetic operator for multiplication, it


can also be used as a dereference operator.

C uses the ">" symbol, defined as a ternary operator, used to evaluate a


conditional expression.

In C, the dot "." symbol is used as the member access operator in


connection with a struct or union type.
C also uses the arrow "" symbol as an indirection operator, used
especially with the pointer to the struct variable.

Operator Description Example

sizeof(a), where a is integer, will return


sizeof() Returns the size of a variable.
4.

&a; returns the actual address of the


& Returns the address of a variable.
variable.

* Pointer to a variable. *a;

If Condition is true ? then value X, else


?: Conditional Expression.
value Y

. Member access operator var.member

Access members of a struct variable with


−> ptr −> member;
pointer

The sizeof Operator in C

The sizeof operator is a compile−time unary operator. It is used to


compute the size of its operand, which may be a data type or a variable.
It returns the size in number of bytes. It can be applied to any data type,
float type, or pointer type variables.

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;

printf("Size of variable a : %d\n",sizeof(a));


printf("Size of int data type : %d\n",sizeof(int));
printf("Size of char data type : %d\n",sizeof(char));
printf("Size of float data type : %d\n",sizeof(float));
printf("Size of double data type : %d\n",sizeof(double));

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

The "&" operator returns the address of an existing variable. We can


assign it to a pointer variable −

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(){

int var = 100;

printf("var: %d address: %d", var, &var);

return 0;
}
Output

Run the code and check its output −

var: 100 address: 931055924

The Dereference Operator in C

To declare a pointer variable, the following syntax is to be used −


type *var;

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;

In this case, the variable x is meant to store the address of


another int variable.

float *y;

The "y" variable is a pointer that stores the memory location of a float
variable.

The "&" operator returns the address of an existing variable. We can


assign it to the pointer 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 −

float var1 = 10.55;


int *intptr = &var1;

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.

Different data types occupy different amounts of memory in C. For


example, an int typically takes 4 bytes, while a float might take 4 or 8
bytes depending on the system.
Adding or subtracting integers from pointers moves them in memory
based on the size of the data they point to.

Hence, we declare the floatptr variable of float * type.

Example 1
Take a look at the following example −

#include <stdio.h>

int main(){

float var1 = 10.55;


float *floatptr = &var1;

printf("var1: %f \naddress of var1: %d \n\nfloatptr: %d \naddress of floatptr: %d", var1,


&var1, floatptr, &floatptr);

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(){

float var1 = 10.55;


float *floatptr = &var1;
printf("var1: %f address of var1: %d\n",var1, &var1);
printf("floatptr: %d address of floatptr: %d\n", floatptr, &floatptr);
printf("var1: %f value at floatptr: %f", var1, *floatptr);

return 0;
}
Output

On running this code, you will get the following output −

var1: 10.550000 address of var1: 6422044


floatptr: 6422044 address of floatptr: 6422032
var1: 10.550000 value at floatptr: 10.550000

The Ternary Operator in C

In C language, the "?" character is used as the ternary operator. It is also


known as a conditional operator.

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.

The ? operator is used with the following syntax −

exp1 ? exp2 : exp3

It has the following three operands −

 exp1 − a Boolean expression that evaluates to True or False


 exp2 − returned by the ? operator when exp1 is true
 exp3 − returned by the ? operator when exp1 is false

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

The conditional operator is a compact representation of if − else


construct.

The Dot (.) Operator in C

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.

Take a look at its syntax −

var.member;

Here, var is a variable of a certain struct or a union type, and member is


one of the elements defined while creating structure or union.

A new derived data type is defined with struct keyword as following


syntax −

struct newtype {
type elem1;
type elem2;
type elem3;
...
...
};

You can then declare a variable of this derived data type as −


struct newtype var;

To access a certain member,

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(){

struct book b1 = {"Learn C", 675.50, 325};


printf("Title: %s\n", b1.title);
printf("Price: %lf\n", b1.price);
printf("No of Pages: %d\n", b1.pages);
printf("size of book struct: %d", sizeof(struct book));

return 0;
}
Output

On running this code, you will get the following output −

Title: Learn C
Price: 675.500000
No of Pages: 325
size of book struct: 32
The Indirection Operator in C

A structure is a derived data type in C. In C, the struct keyword has been


provided to define a custom data type.

A new derived data type is defined with a struct keyword as the


following syntax −

struct type {
type var1;
type var2;
type var3;
...
...
};

You can then declare a variable of this derived data type as −

struct type = var;

Usually, a struct is declared before the first function is defined in the


program, after the include statements. That way, the derived type can be
used for declaring its variable inside any function.

Let us declare a struct type named book as follows −

struct book {
char title[10];
double price;
int pages;
};

To declare a variable of this type, use the following syntax −

struct book b1;

The initialization of a struct variable is done by placing value of each


element inside curly brackets.

struct book b1 = {"Learn C", 675.50, 325};

You can also store the address of a struct variable in the struct pointer
variable.
struct book *strptr;

To store the address, use the "&" operator.

strptr = &b1;

C defines the arrow () symbol to be used with struct pointer as indirection


operator (also called struct dereference operator). It helps to access the
elements of the struct variable to which the pointer reference to.

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

Run the code and check its output −

Title: Learn C
Price: 675.500000
No of Pages: 325

You might also like