Copyright © Programs ++
Design by Dzignine
Monday, 30 January 2012

Multiple increment operators in a sinlge expression

I came across this problem while reading a program in my sophomore year. When multiple increment operators are used in a single statement, the results can be quite unpredictable. For e.g, consider this piece of code :
int C,a = 10;
C = a++ + ++a + ++a + a;
std::cout<<C<<" "<<a;

Now, usually the compiler evaluates the expression from right to left, and hence the result should come out to be 10 + 11 + 12 + 12 = 45(if my math is correct :p), but when the program is executed, the result comes out to be 12 + 12 + 12 + 12 = 48( :O ). Does this mean that the computer made a mistake ?? No, the compiler did not. What happened actually is that when multiple increment operators are used in a single statement, the compiler 
1 - first evaluates all the prefix expressions i.e. ++a leading the value of 'a' to be 11 then again ++a, thus 'a' becomes 12.
2 - then the expression is evaluated, so the expression becomes 12 + 12 + 12 + 12 = 48;
3 - finally it evaluates the postfix expressions i.e a++ hence the the final value of 'a' becomes 13.
The following program demonstrates the above concept :

// Multiple incremnet operators in a single expression

#include <iostream>

int main()
{
    int a = 10,result;
    result = a++ + ++a + ++a + a;
    std::cout<<" Result : "<<result; // displays the result
    std::cout<<" \n Value of a : "<<a; // displays the value of a
    std::cin.get();  
    return 0;
} // end of main
Output in turbo compiler












NOTE : The above output is obtained when the program is executed using a turbo C++ compiler or a borland c++ compiler. 
The way in which the expression is evaluated varies from compiler to compiler. For e.g, when the same program is executed in Dev-C++, the result comes out to be 46. Hence different compilers evaluate an expression containing multiple increment operators differently.
Output in dev-c++









  




------Related Posts ------

http://programsplusplus.blogspot.com/2012/01/4-pre-and-post-increment-operators.html

2 comments:

  1. First it evaluates Post fix operators then it go for prefix operators...According to precedence of operators ....And it may vary from compiler to compiler :)

    ReplyDelete
  2. actually that is what this post is all about, when multiple increment operators are used in a single statement, then the behavior is UNDEFINED, as the compiler does not have any rules for performing such an operation. Even thought such operators are evaluated as per normal rules, but when used in a single statement, the results are different across different compilers. Hence different outputs. :)

    ReplyDelete

Comment Here....