Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
772 views
in Technique[技术] by (71.8m points)

c - issue with assignment operator inside printf()

Here is the code

int main()
{
  int x=15;
  printf("%d %d %d %d",x=1,x<20,x*1,x>10);
  return 0;
}

And output is 1 1 1 1

I was expecting 1 1 15 1 as output,

x*1 equals to 15 but here x*1 is 1 , Why ? Using assignment operator or modifying value inside printf() results in undefined behaviour?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code produces undefined behavior. Function argument evaluations are not sequenced relative to each other. Which means that modifying access to x in x=1 is not sequenced with relation to other accesses, like the one in x*1. The behavior is undefined.

Once again, it is undefined not because you "used assignment operator or modifying value inside printf()", but because you made a modifying access to variable that was not sequenced with relation to other accesses to the same variable. This code

(x = 1) + x * 1

also has undefined behavior for the very same reason, even though there's no printf in it. Meanwhile, this code

int x, y;
printf("%d %d", x = 1, y = 5);

is perfectly fine, even though it "uses assignment operator or modifying value inside printf()".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...