Unable to understand the pre-increment operation

When I executed the following code in the visual c++ or turbo c compiler, its giving the output value as '12' but it should give '9' I think so... Please clarify my doubt...
#include<stdio.h>
#include<conio.h>
main()
{
int a=1,b=0;
b=++a + ++a + ++a;
printf("%d\n",b);
getch();
}
it's undefined, you can't do it that way, for example I get 10, this is how you would do it properly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{
    int a = 1;
    int b = 0;

    b += ++a;
    b += ++a;
    b += ++a;

    std::cout << b << std::endl;
    std::cout << a << std::endl;
    return 0;
}


1
2
3
//output
9
4
Last edited on
It's, like most "undefined" stuff, it's actually implementation defined. In your and my compiler all prefix operators in an expression are executed on all the occurrences of that variable, and postfix operators work only on those after itself.
@viliml
The standard clearly states it is undefined so it's not implementation defined. We had this discussion not long ago http://cplusplus.com/forum/general/76215/
+1 @ Zephilinox & Peter87

You should never ever write code like this.
Topic archived. No new replies allowed.