Unexpected output after running this little bit strange c code. Can anyone explain how this happened?

Viewed 89

I am trying to understand how this code works,

int main () {
 int m, k;
 m = (k=5)+(k=8)+(k=9)+(k=7);
 printf("m=%d\n",m);
 printf("k=%d\n",k);
}

The output: m=32 k=7

I have no idea how is the value of m become 32. I hope someone can help me to understand how this code works and how the outputs end up like this

3 Answers

Simplified explanation:

When you use k=... multiple times in the same expression, all assignments to that same variable are so-called "unsequenced side-effects". Simply put, it means that C doesn't specify which operand of + to evaluate/execute first nor does it specify the order in which the assignments will get carried out.

So the compiler has no way of knowing which k to evaluate/assign to first and therefore gets all confused. This is so-called "undefined behavior", anything can happen.

You have to solve this by splitting the expression up in several, each separated by a semicolon, which acts as a "sequence point", meaning all prior evaluations need to be done at the point where the ; is encounterd. Example:

k=5;
k+=8;
k+=9;
m = k + 7;

Detailed explanation with standard references here: Why can't we mix increment operators like i++ with other operators?

The behaviour of the program is undefined.

There are multiple unsequenced writes on k in the expression

(k = 5) + (k = 8) + (k = 9) + (k = 7)
Related