Assignment operators in C

 Assignment operators are used to assign values to variables.  Consider the following,


int val = (10 + 5);

Here, assignment operator assigns the resultant value of the expression at the right side to left operand.

Below are some of the compound assignment operators available in C language.

OperatorExpressionEquivalent Expression
 += x += 200 x = x + 200
 -= x -= 200 x = x - 200
 *= x *= 200 x = x * 200
 /= x /= 200 x = x / 200
 %= x %= 200 x = x % 200
 <<= x <<= 2 x = x << 2
 >>= x >>= 2 x = x >> 2
 &= x &= 2 x = x & 2
 ^= x ^= 2 x = x ^ 2
 |= x |= 2 x = x | 2


Example C program using assignment operators:
 
  #include <stdio.h>
  int main() {
        int a, b, c, d, e;  // variable declaration
        a = b = c = d = e = 100;  // assign 100 to a, b, c, d & e

        a += 10; // a = a + 10
        printf("Value of a is %d\n", a);

        b -= 10; // b = b - 10
        printf("Value of b is %d\n", b);

        c *= 10; // c = c * 10
        printf("Value of c is %d\n", c);

        d /= 10; // d = d / 10
        printf("Value of d is %d\n", d);

        e %= 10; // e = e % 10
        printf("Value of e is %d\n", e);
        return 0;
  }


  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Value of a is 110
  Value of b is 90
  Value of c is 1000
  Value of d is 10
  Value of e is 0

No comments:

Post a Comment