Can someone tell me how this code works?
#include <stdio.h>
void main() {
int m,k;
m=(k=5) + (k=8) + (k=9) + (k=7);
printf ("%d\n", m);
} // output 32
When I run this code in my compiler, the output was 32.
Don't know why.
Can someone tell me how this code works?
#include <stdio.h>
void main() {
int m,k;
m=(k=5) + (k=8) + (k=9) + (k=7);
printf ("%d\n", m);
} // output 32
When I run this code in my compiler, the output was 32.
Don't know why.
This code invokes undefined behavior - any result is suspect, even if it’s the result you expect.
Attempting to modify an object more than once (or modifying it and using it in a value computation) in an expression without a sequence point leads to undefined behavior. The multiple assignments to k are a problem. The thing is, arithmetic expressions don’t have to be evaluated left to right - each term can be evaluated in any order. Additionally, side effects don’t have to be applied immediately after evaluation.
Any result you get is the result of accident, not design.
k = k+1 undefined, which it is not.k are the problem. m = 5 + 8 or m = 5 + 8 + 9 + 7 will work. Even something like m = (a=5) + (b=8) + (c=9) + (d=7) will work as expected because you're not updating the same object multiple times without a sequence point. But updating k multiple times is causing the compiler to generate code that gives an undefined result, where "undefined" just means that the compiler isn't required to handle the situation in any particular way.