简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM