How to explain the output of the below code:
include <stdio.h>
int main(void) {
int k;
printf("%d %d\n",k=1,k=3);
return 0;
}
Ideone Link
My thinking was that 1
will be assigned to k
variable and then 1
would be printed. Similarly 3
will be assigned to k
and output will be 3
.
Expected Output
1 3
Actual Output
1 1
I am extrapolating from
int a;
if (a = 3) {
...
}
is equal to
if (3) {
...
}
Please let me know where am I going wrong?
The problem is, the order of evaluation of function arguments are not defined, and there's no sequence point between the evaluation or arguments. So, this statement
printf("%d %d\n",k=1,k=3)
invokes undefined behavior, as you're trying to modify the same variable more than once without a sequence point in between.
Once a program invoking UB is run and (if) there's an output, it cannot be justified anyway, the output can be anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With