Operators and Expressions

Operators and Expressions

There are various operators defined in C language. Different types of operators in C language are: Arithmetic, Relational, Logical, Bitwise, Assignment and Special operators.

  • Arithmetic Operators 

C provides all the basic arithmetic operators. Following are the arithmetic operators in C: -

Operator        Description

   +                   Addition

   -                    Subtraction

   *                   Multiplication

   /                    Division

  %                  Modulus

  --                   Decrement

 ++                  Increment


+ and – comes in to variants as they can be used as unary operators and binary operators both. In case of unary - acts as returning the negative value, which is used to represent negative values for example,


int b = 10;
int a = -b;   // a will be -10 now.


+, -, *, / will act in usual behavior, returning addition, subtraction, multiplication and division (quotient) of two operands. % (modulus) returns the division (remainder) instead quotient. 

For example:-

#include <stdio.h>
int main()
{
      int a, b, c, d;
      a=5;
      b=2;
      c=1;
      d=2;
      printf("a=%d b=%d c=%d d=%d \n\n",a,b,c,d);
      printf("a+b = %d\n", a + b);
      printf("a-b=%d\n", a - b);
      printf("a*b = %d\n", a * b);
      printf("a/b = %d\n", a / b);
      printf("a%%b = %d\n\n", a % b);
      printf("c+d = %d\n", c + d);
      printf("c-d = %d\n", c - d);
      printf("c*d = %d\n", c * d);
      printf("c/d = %d\n", c / d);
      printf("c%%d = %d\n", c % d);
  return 0;
}
Output:


++ and -- are two operators which are required for quick addition and subtraction. If we need unit increment or decrement, we can use these operators. 
For example:
int x=5;
x = x + 1;   // x will be 6 now onwards.
int y=5;
y++;      // y will be 6 now onwards.
int a=10;
a--;      // a will be 9 now onwards.
int b =10;
b = b – 1;   // b will be 9 now onwards.
So, a++ is same as a = a + 1 and a-- is same as a = a – 1.


Both increment and decrement operators can either be prefix to operand or postfix to operand, in those case, there are called as,

a++;   // post increment

++a;   // pre increment

a--;    // post decrement

--a;    // pre decrement


  • Relational Operators

Suppose we compare two quantities and depending on their relation, take certain decisions. For example, we may compare the price of two items, or age of two persons. So these comparisons can be done using relational operators.

In C language, we can define true and false outputs based on some conditions. Any value other than 0 (ZERO) in C is treated as true, whereas ZERO is false. Be careful, all positive and negative numbers other than 0 are true, only 0 is treated as false in C language.

Relational operators return 0 when they found a false result, and 1 if they found a true result based on their conditions. Following are the relational operators: -

Operators       Description
     >                greater than
    >=               greater than or equal
     <                less than
    <=               less than or equal
    ==               equal
    !=                not equal


We can check any two expressions with these relational operators. For example,

4 > 5;        // return 0 as condition is false.
4 == 4;      // return 1 as they match
3 != 6;       // return 0 as condition is false.
4 <= 9;      // return 1 as condition satisfies
Program:

#include <stdio.h>
int main()
{
  int a,b,c,d;
  a=5;
  b=2;
  c=5;
  d=8;
  printf("a=%d b=%d c=%d d=%d \n\n",a,b,c,d);
  if(a > b) printf("a is greater than b.\n");
  if(a >= d) printf("a is greater than or equal to d.\n");
  if(a == c) printf("a is equal to c.\n");
  if(a != d) printf("a is not equal to d.\n");
  if(d <= c) printf("d is less than or equal to c.\n");
  if(d > c) printf("d is greater than c.\n");
  return 0;
}

Output:


  • Logical Operators

Logical operators are used to combine the conditions.

Operators       Descriptions
   &&                 AND
     ||                    OR
     !                    NOT
The logical operators && and || are used when we want to test more than one condition and make decisions.

Truth Table:
A    B    A&&B    A||B    !A
0     0         0           0        1
0     1         0           1        1
1     0         0           1        0
1     1         1           1        0
   

In C, from values, operands will be evaluated to either 0 or 1. These are used to combine relational operations, for example,


(3 > 1) && (5 != 6)   // combining two conditions. Evaluated as (1 && 1) = 1
(1 > 3) && (5 != 6)   // combining two conditions. Evaluated as (0 && 1) = 0
(1 > 3) || (5 != 6)       // combining two conditions. Evaluated as (0 || 1) = 1

Program:

#include <stdio.h>
int main()
{
  int a,b,c,d;
  a=5;
  b=2;
  c=5;
  d=8;
  printf("a=%d b=%d c=%d d=%d \n\n",a,b,c,d);
  if((a > b) && (a == c)) printf("a is greater than b AND a is equal to c.\n");
  if((a <= b) && (d >= b)) printf("a is less than b AND d is greater than b.\n");
  if((a != b) && (a <= d)) printf("a is not equal to b AND a is less than or equal to d.\n");
  return 0;
}
Output:


  • Bitwise Operators

C has a distinction of supporting special operators know as bitwise operators for manipulation of data at bit level. Bitwise operators work on individual bits and bytes of operands. Bitwise operators works on char and int variables only and may not be applied to float or double.
Operator   Description
    &             AND
     |               OR
    ^              XOR
    ~              NOT
   >>         Right Shift
   <<          Left Shift

The bit-shift operators, >> and <<, move all bits in a variable to the right or left as specified. The general form of the shift-right statement is

   variable >> number of bit positions

The general form of the shift-left statement is

   
variable << number of bit positions

As bits are shifted off one end, zeroes are brought in the other end. (In the case of a signed, negative integer, a right shift will cause a 1 to be brought in so that the sign bit is preserved.) Remember, a shift is not a rotate. That is, the bits shifted off one end do not come back around to the other. The bits shifted off are lost.

For example:
 
Output:

Eventually, if you shift a number k bit right, you are yielding quotient(number / (2^k)). And if you shift a number k bit left, you are yielding (number * (2^k)).

  • Assignment Operators

Assignment operators are used to assign the result of an expression to a variable. In C, ( = ) equals sign is a assignment operator. It takes two operands. First on left side whose value will get the new value assigned (known as lvalue), and second on right side whose value will be assigned to lvalue (known as rvalue). 
For example:
int a=25;   // a (lvalue) will be assigned 25 (rvalue).
char c='A';   // c (lvalue) will be assigned 'A' (rvalue).

lvalue is an object, which refers to a memory location, it should be modifiable otherwise you will get an error. 

For example:
5 = 6;      // 6 is correct rvalue, but 5 is not an lvalue, as 5 is a constant value not a location.

You can assign multiple variables in a single statement as below: -
int a, b, c, d;
a = b = c = d = 10;      // it will assign 10 to all these variables.

Assignment operator start assignment from right side and returns the rvalue, hence, first d will be assigned 10, and it returns 10, so next c will be assigned 10, and so on.


  • Special Operators

The & and * operators
These are used with pointer management.

sizeof operator
sizeof is a unary compile-time operator that returns the length, in bytes, of the variable or parenthesized type specifier that it precedes. 

Comma operator
The comma operator can be used to link the related expressions together. It is used to sequencing of operations. If multiple operations are to be performed, we can sequence them using comma operator. It is quite tricky sometimes to use this operator.


Precedence and Associativity of operators
Precedence   Operators       Associativity

   Highest              () [] . ?             Left to right   
                                                   (Parentheses etc.)

                      ! ~ ++ -- sizeof       Right to left   
                       + - * & (type)   (Unary operators)
        
                             * / %                Left to right   
                                                     (Arithmetic)

                              +  -                   Left to right   
                                                     (Arithmetic)

                            >> <<                Left to right   
                                                    (Bitwise Shift)

                         < <= > >=             Left to right  
                                                      (Relational)

                            == !=                 Left to right   
                                                      (Relational)

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

                               ?:                    Right to left   
                                                      (Conditional)

                    = += -+ *= /+ *=       Right to left   
                    %= &= ^= |= >>=   (Assignment)
                      
Lowest                    ,                    Left to right   
                                                       (Comma)


Expressions in C:

An expression is a combination of operators and operands which reduces to a single value.
 
Operand: An operand is a data item on which an operation is performed.

Operator: An operator indicates an operation to be performed on data.

Types of expressions:

1) Primary
    c=a+(5*b)

2) Postfix
    z=a++

    z=a
    then
    a=a+1

3) Prefix
    z=++a
    
    a=a+1
    then
    z=a

4) Unary
    a++
    b--

5) Binary
    a=b
    c*d

6) Ternary
    3 oprands & 1 operator
    Exp1?Exp2:Exp3

Post a Comment

If you have any doubts, Please let me know

Previous Post Next Post