C - output description printf ("% d% d \ n", k = 1, k = 3);
How to explain the code output below:
include <stdio.h> int main(void) { int k; printf("%d %d\n",k=1,k=3); return 0; } I thought 1 would be assigned to the variable k , and then 1 would be printed. Similarly, 3 will be assigned k , and the output will be 3 .
Expected Result
1 3 Actual output
1 1 I extrapolate from
int a; if (a = 3) { ... } equally
if (3) { ... } Please let me know where I am going wrong?
The problem is that the evaluation order of the arguments to the function is not defined, and there is no point in the sequence between the evaluation or the arguments. So this statement
printf("%d %d\n",k=1,k=3) causes undefined behavior as you try to change the same variable more than once without a sequence point between them.
As soon as the program invoking UB is launched, and (if) there is a way out, this cannot be justified in any way; the output can be any.
I expect that the reason you see 1 1 is because two assignment statements are executed, control is passed to printf .
printf("%d %d\n",k=1,k=3); So, in response to lowering voices, yes, this behavior is undefined, and therefore you should not expect this behavior to continue. However, from the point of view of determining why the conclusion was 1 1 and not 1 3 , we could conclude that assignment 3 could be overturned by the subsequent assignment of 1 .
When printf is called, the call stack contains two entries containing the final value of k , which is 1 .
You can verify this by replacing them with a function that prints something when it runs.
Code example:
#include <stdio.h> int test(int n) { printf("Test(%d)\n", n); return n; } int main(void) { int k; printf("%d %d\n",k=test(1), k=test(3)); return 0; } Output:
Test(3) Test(1) 1 1