1

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.

1
  • 1
    Your code invokes undefined behavior by assigning to the same variable multiple times in a single statement, meaning that anything can happen. Commented May 18, 2021 at 3:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Re “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”: That would make k = k+1 undefined, which it is not.
Seems so... A small request to you can you try: m=(k=5) + (k=8); // output 16 m=(k=8) + (k=5); // output 10 instead of m=(k=5) + (k=8) + (k=9) + (k=7); --> which is double of the last value of k.
@ApoorvPathak: Again, those expressions cause undefined behavior - the multiple updates to 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.