#include <stdio.h>
main() {
int i=3,j;
j=++i*++i*++i;
printf("%d,%d",i,j);
}
The answer is upcoming up with i=6, j=150 Please explain why j is coming up with 150??
#include <stdio.h>
main() {
int i=3,j;
j=++i*++i*++i;
printf("%d,%d",i,j);
}
The answer is upcoming up with i=6, j=150 Please explain why j is coming up with 150??
This Undefined behaviour is because of Sequence Points. See these links
This j=++i*++i*++i
in your compiler will break into 1:(++i*++i)*++i
then it will calculate the left operand and then the right one. The left one is a parenthesis so it will see what's inside. That ++i*++i
will be evaluated as (++i)*(++i)
, then the compiler will calculate the left and right operands and then it will do the multiplication. The left operand will increase i
by one and return i
, right operand will increase i
by one and will return i
. So we got i*i
in the first parenthesis of the 1
expression, i
is 5
so it will return 25
. Now we got (25)*(++i)
, compiler checks both operands, left one returns 25
, right one increases i
by one and returns i
, i
is now 6
so we got 25*6=150
. This is how gcc works
The result is actually depend on the compiler.
I have compiled it with gcc and clang. Gcc outputs 150, and clang outputs 120.
But the disassemble can give the reason why j = 150:
movl $0x3,-0xc(%rbp) // i = 3
movl $0x0,-0x10(%rbp) // j = 0
mov -0xc(%rbp),%eax // %eax = i = 3
add $0x1,%eax // %eax += 1, %eax = 4
mov %eax,-0xc(%rbp) // move %eax back to i, ie i = 4
mov -0xc(%rbp),%eax // %eax = i = 4
add $0x1,%eax // %eax = 5
mov %eax,-0xc(%rbp) // move %eax back to i, ie i = 5
mov -0xc(%rbp),%eax // store i in %eax
mov -0xc(%rbp),%ecx // store i in %ecx
imul %ecx,%eax // %eax * %ecx, %eax = 5*5 = 25
mov -0xc(%rbp),%ecx // store i in %ecx
add $0x1,%ecx // %ecx + 1, %ecx = 6
mov %ecx,-0xc(%rbp) // move %ecx back to i, ie i = 6
mov -0xc(%rbp),%ecx // store i in %ecx
imul %ecx,%eax // %eax * %ecx, %eax = 6*25=150
mov %eax,-0x10(%rbp) // move %eax to j, ie j = 150