Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Output explanation of printf("%d %d\n",k=1,k=3); [duplicate]

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?

like image 950
jayd Avatar asked Oct 17 '22 16:10

jayd


1 Answers

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.

like image 63
Sourav Ghosh Avatar answered Oct 21 '22 07:10

Sourav Ghosh