0

The following code

#include <stdio.h>

int main(){
    int a = 9;
    printf("%d\n", a);
    printf("%d, %d, %d\n",a,  (a=10), a);

    return 0;
}

prints the following output along with the warning

main.c: In function ‘main’:
main.c:8:31: warning: operation on ‘a’ may be undefined
   printf("%d, %d, %d\n",a,  (a=10), a);
                               ^
main.c:8:31: warning: operation on ‘a’ may be undefined

9
10, 10, 10

Now, I understand that return value of assigning one variable to some value is the value that has been assigned to(Low level details of C/C++ assignment operator implementation. What does it return?.). But interestingly, printing variable 'a' even before assignment is printing 10 instead of 9. Why is it so? It looks like assignment of a is being completed and then all other value is printed. But is it compiler dependent behavior or specified in C, which I didn't find any reference for.

Delsilon
  • 156
  • 12
  • 1
    The order of evaluation of arguments is undefined in C. Looking for a suitable duplicate... [This answer](https://stackoverflow.com/a/2397995/10871073) may help. – Adrian Mole Jun 03 '20 at 13:02
  • There's no order to the evaluation of arguments. Those `a` could all be 9, they could all be 10, or it could be some mix of the two. This could change depending on your level of optimization, platform, etc. – Thomas Jager Jun 03 '20 at 13:02
  • okay, https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior, i found the duplicate here. – Delsilon Jun 03 '20 at 13:04
  • https://en.wikipedia.org/wiki/Sequence_point – William Pursell Jun 03 '20 at 13:04
  • 1
    Maybe this one: https://stackoverflow.com/q/2397984/10871073 – Adrian Mole Jun 03 '20 at 13:05
  • Relevant: [Order of evaluation of arguments in function calling?](https://stackoverflow.com/questions/22616986/order-of-evaluation-of-arguments-in-function-calling) – Weather Vane Jun 03 '20 at 13:10

0 Answers0