# Thread: analyze the answer for the code

1. ## analyze the answer for the code

Code:
```main()
{
int i=5,j=5,p,q;
p=(i++)+(i++)+(i++);
q=(++j)+(++j)+(++j);
printf("%d,%d,%d,%d",p,q,i,j);
}```
I ran the program and it is showed 22 for q. How can I get 22 for q? Thank you very much.

2. Interesting. I get 22 as well. Coding

a = ++j ;
b = ++j ;
c = ++j ;
z = a+b+c ;

I get 21, which is what I would have expected with the original (6 + 7 + 8).

3. But the solution on the book is given 24, which is 8+8+8. It is weird.

4. I would have guessed 24 as my second guess!

Perhaps this is one of those "undefined behavior" situations.

5. Disassembling the following code using gcc:
Code:
```int j=5;
int q=(++j)+(++j)+(++j)```
results in:
Code:
```...
movl   \$0x5,0xfffffffc(&#37;ebp)
lea    0xfffffffc(%ebp),%eax
incl   (%eax)
lea    0xfffffffc(%ebp),%eax
incl   (%eax)
mov    0xfffffffc(%ebp),%eax
mov    0xfffffffc(%ebp),%edx
lea    0xfffffffc(%ebp),%eax
incl   (%eax)
mov    %edx,%eax
...```
Leading, if I'm not wrong, to something like 7+7+8 (=22).
So the evaluation is probably indeed undefined and thus the case 8+8+8 is an acceptable alternative.

6. Right, this question crops up every now and again, and it's just as undefined this time as last time someone asked (although that time it was about x++*x++*x++).

The compiler is allowed to "do as it likes" with all those ++ calculations, and some compilers will perform this in a different way than others. Realistically, any answer between 15 and 24 is likely, and since it's in the "undefined behaviour land" (which is a bit like Wonderland that Alice went to), you could also get completely and utterly rubbish answers.

If you really want to do something like that, then you should write it out as you want it done, e.g.
Code:
```
q = j+1 + j+2 + j+3;
// Which can be simplified as:
q = j*3 + 6;
// Which becomes:
q = 15+6 -> 21.```
And by the way, when optimizing this code in gcc (gcc -O2 -S x.c):
Code:
```  int j=5;
int q=(++j)+(++j)+(++j);
printf("q = %d, j = %d\n", q, j);```
it comes up with 22:
Code:
```        movl    \$8, %edx
movl    \$22, %eax
movl    %edx, 8(%esp)
movl    %eax, 4(%esp)
call    _printf```
--
Mats

Popular pages Recent additions