Wednesday, July 10, 2013

What happens to Operator Precedence in Compound Assignment

We know that as per the Operator precedence, the multiplication has more precedence than that of addition. Also we know that in when we write a compound assignment notation as,
x*=3, it means x=x*3;
So, when it comes to a equation like,
x*=a+b, 
What happens with the equation. How does the Operator precedence takes place. Check out the following program first,

  1. #include<stdio.h>
  2. main()
  3. {
  4. int a=2,b=3,x=5;
  5. x*=a+b;
  6. printf("%d",x);
  7. return 0;
What will be the output of the program??

As per the operator precedence, we expect the answer as 13, because the equation is resolved into x=x*a+b. But if we think like that, it is a big mistake.

In Compound Assignment Operator, before resolving the equation, it first calculates the expression on the right side first and then resolves the equation. So the resolved equation comes to be as,

x=5*(2+3);

Hence the result comes to be as 25, rather than 13.