I ran the program and it is showed 22 for q. How can I get 22 for q? Thank you very much.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.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); }
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).
Mainframe assembler programmer by trade. C coder when I can.
But the solution on the book is given 24, which is 8+8+8. It is weird.
I would have guessed 24 as my second guess!
Perhaps this is one of those "undefined behavior" situations.
Mainframe assembler programmer by trade. C coder when I can.
Disassembling the following code using gcc:
results in:Code:int j=5; int q=(++j)+(++j)+(++j)
Leading, if I'm not wrong, to something like 7+7+8 (=22).Code:... movl $0x5,0xfffffffc(%ebp) lea 0xfffffffc(%ebp),%eax incl (%eax) lea 0xfffffffc(%ebp),%eax incl (%eax) mov 0xfffffffc(%ebp),%eax mov 0xfffffffc(%ebp),%edx add %eax,%edx lea 0xfffffffc(%ebp),%eax incl (%eax) mov %edx,%eax add 0xfffffffc(%ebp),%eax ...
So the evaluation is probably indeed undefined and thus the case 8+8+8 is an acceptable alternative.
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.
And by the way, when optimizing this code in gcc (gcc -O2 -S x.c):Code:q = j+1 + j+2 + j+3; // Which can be simplified as: q = j*3 + 6; // Which becomes: q = 15+6 -> 21.
it comes up with 22:Code:int j=5; int q=(++j)+(++j)+(++j); printf("q = %d, j = %d\n", q, j);
--Code:movl $8, %edx movl $22, %eax movl %edx, 8(%esp) movl %eax, 4(%esp) call _printf
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.