So just for fun, I have this code snippet:
#include <stdio.h>
main()
{
int i;
int a;
i = 17;
//scanf("%d", &i);
a = (i+=5) * (i-=3);
printf("a is %d, i is %d\n", a, i);
}
In C specifications, it says the order of operands evaluation is undefined, so I was expecting to see either 22 * 19, or 19 * 14. However, the result is 19 * 19:
~ $ gcc a.c
~ $ ./a.out
a is 361, i is 19
I thought about it, and the only explanation I could come up with is that the compiler did a 'delayed' evaluation on (i+=5)
's value, and it thought that (i+=5)
's value is just value of i. same for (i-=3)
.
However, if I uncomment the scanf()
:
#include <stdio.h>
main()
{
int i;
int a;
i = 17;
scanf("%d", &i);
a = (i+=5) * (i-=3);
printf("a is %d, i is %d\n", a, i);
}
Now I input 17 at prompt:
~ $ gcc a.c
~ $ ./a.out
17
a is 418, i is 19
Why does it show different behavior?