C Operators

An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C language.

  • Arithmetic Operators
  • Relational Operators
  • Shift Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary or Conditional Operators
  • Assignment Operator
  • Misc Operator
  • Increment/Decrement operator
  • Conditional (Ternary) operator
  • Shift Operators

Arithmetic Operators

The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then

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 integer division. B % A = 0
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then

Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. (A <= B) is true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. (A || B) is 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 false. !(A && B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is 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

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) = 12, i.e., 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) = 49, i.e., 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) = -60, i.e,. 1100 0100 in 2's complement form.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 = 240 i.e., 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 = 15 i.e., 0000 1111

Assignment Operators

The following table lists the assignment operators supported by the C language

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary

Besides the operators discussed above, there are a few other important operators including sizeof and ? : supported by the C Language.

Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
* Pointer to a variable. *a;
? : Conditional Expression. If Condition is true ? then value X : otherwise value Y

Increment and Decrement operator in C

September 12, 2017C programmingC, Programming, TutorialPankaj Prakash

Quick links

Syntax

Prefix vs Postfix

Increment and Decrement operator are used to increment or decrement value by 1.

There are two variants of increment/decrement operator.

  • Prefix (pre-increment and pre-decrement)
  • Postfix (post-increment and post-decrement)

Syntax of increment/decrement operator

SyntaxDescriptionExample
++<variable-name>Pre increment++a
<variable-name>++Post incrementa++
--<variable-name>Pre decrement--a
<variable-name>--Post decrementa--

Important note: ++ and -- operators are used with variables. Using ++ or -- with constant will result in error. Such as expressions like 10++, (a + b)++ etc. are invalid and causes compilation error.

Let us consider an integer variable int a = 10;. To increment a by 1, you can use either

a = a + 1 (Simple assignment)

a += 1 (Shorthand assignment)

a++ (Post increment)

++a (Pre increment)

Result of all the above code are similar.

Prefix vs Postfix

Both prefix and postfix does same task of incrementing/decrementing the value by 1. However, there is a slight difference in order of evaluation.

Prefix first increment/decrements its value then returns the result. Whereas postfix first returns the result then increment/decrement the value.

To understand this efficiently let’s consider an example program





#include <stdio.h>

int main()
{
    int a, b, c;

    a = 10;   // a = 10
    b = ++a;  // a=11, b=11
    c = a++   // a=12, c=11

    printf("a=%d, b=%d, c=%d", a, b, c);

    return 0;
}



Output of above program is a=12, b=11, c=11. Let us understand the code.

a = 10 Assigns 10 to variable a

b = ++a Since we have used prefix notation. Hence, first it increments the value of a to 11, then assigns the incremented value of a to b.

c = a++ Here we have used postfix notation. Hence, first it assigns the current value of a i.e. 11 to b, then increments the value of a to 12.

Important note: Never use postfix and prefix operator at once otherwise it will result in error. Such as ++a++, ++a-- both results in compilation error.

Conditional operator is a ternary operator used to evaluate an expression based on some condition. It is a replacement of short if...else statement.

Syntax of conditional operator




 ?  : 



It accepts three operands, conditional-expression, true-expression and false-expression.

The conditional-expression is followed by ? symbol, followed by true-expression. true-expression is followed by : symbol and false-expression.

If conditional-expression is true then true-expression gets evaluated otherwise false-expression. In no case both the expressions are evaluated.

The above conditional expression is equivalent to





if(conditional-expression)
{
    // true-expression
}
else
{
    // false-expression
}



Example program of conditional operator

Consider the below program to find maximum between two numbers using conditional operator.




 
#include <stdio.h>

int main()
{
    int num1 = 10;
    int num2 = 20;

    /*
     * If (num > num2) then
     *    assign num1 to max
     * else
     *    assign num2 to max
     */
    int max = (num1 > num2) ? num1 : num2;

    printf("Maximum is %d.", max);

    return 0;
}



In the above program prints Maximum is 20.. Since the condition (num1 > num2) is false therefore false-expression gets evaluated assigning 20 to max.

Practice to learn - Conditional operator programming exercises and solutions

Important note: Always feel free to transform single if...else statement to conditional operator expression, if it makes your code more readable and clear. However, it is never recommended to transform a nested if...else...if or ladder if...else statement to conditional operator expression.

C Bitwise Right Shift : (>>) Operator

In the previous chapter we have learnt about Bitwise Left Shift Operator. In this chapter we are looking into Bitwise Right Shift Operator.

Bitwise Right Shift Operator in C

1.It is denoted by >>

2.Bit Pattern of the data can be shifted by specified number of Positions to Right

3.When Data is Shifted Right , leading zero’s are filled with zero.

4.Right shift Operator is Binary Operator [Bi – two]

5.Binary means , Operator that require two arguments

Quick Overview of Right Shift Operator

Original Number A 0000 0000 0011 1100
Right Shift by 2 0000 0000 0000 1111
Leading 2 Blanks Replaced by 0 ,Shown in RED
Direction of Movement of DataRight ========>>>>>>

Syntax :

[variable]>>[number of places]

Live Example : Bitwise Operator [Right Shift Operator]




#include<stdio.h>

int main()
{
int a = 60;

printf("\nNumber is Shifted By 1 Bit  : %d",a >> 1);
printf("\nNumber is Shifted By 2 Bits : %d",a >> 2);
printf("\nNumber is Shifted By 3 Bits : %d",a >> 3);

return(0);
}



Output :




Number is Shifted By 1 Bit  : 30
Number is Shifted By 2 Bits : 15
Number is Shifted By 3 Bits : 7



Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the operators direction to be evaluated, it may be left to right or right to left.

Let's understand the precedence by the example given below:




int value=10+20*10;  



The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).

The precedence and associativity of C operators is given below:

Category OperatorAssociativity
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



Instagram