Shyam Prasanna
Shyam Prasanna

Reputation: 111

Confusion in assignment in c

#include<stdio.h>
int main()
{
 int a=0, b=1, c=3;
 *((a) ?&b :&a) = a ? b : c; 
 printf("%d %d %d\n", a, b, c);
 return 0;
}

Output:3 1 3

The associativity for assignment operator is right to left . So here we got 3 1 3 but ...

#include<stdio.h>
int main()
{
 int a=0, b=1, c=3;
 *((a++) ?&b :&a) = a ? b : c;
 printf("%d %d %d\n", a, b, c);
 return 0;
}

Output : 1 1 3

My doubt is why 1 1 3 is returned instead of 1 3 3 ?

Upvotes: 1

Views: 84

Answers (1)

dbush
dbush

Reputation: 224437

What you have here is a manifestation of undefined behavior.

Order of operations only dictate how operands are grouped. It does not dictate the order in which subexpressions are evaluated.

In this expression:

*((a++) ?&b :&a) = a ? b : c;

The only guarantee is that a++ will be evaluated before either &b or &a, and that a will be evaluated before either b or c. There is no sequencing between the evaluation of a++ and a, so you have a read and a write of a variable without a sequence point.

Upvotes: 6

Related Questions