printf(“%d %d %d\n”,++a, a++,a) output [duplicate]

别等时光非礼了梦想. 提交于 2019-12-17 15:59:12

问题


Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

I'm not able to understand the output of this program (using gcc).

main()
{
  int a=10;
  printf("%d %d %d\n",++a, a++,a);
}

Output:

12 10 12

Also, please explain the order of evaluation of arguments of printf().


回答1:


The compiler will evaluate printf's arguments in whatever order it happens to feel like at the time. It could be an optimization thing, but there's no guarantee: the order they are evaluated isn't specified by the standard, nor is it implementation defined. There's no way of knowing.

But what is specified by the standard, is that modifying the same variable twice in one operation is undefined behavior; ISO C++03, 5[expr]/4:

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

printf("%d %d %d\n",++a, a++,a); could do a number of things; work how you expected it, work in ways you could never understand, crash, blow up, or if it's feeling particularly witty, send nasty emails to your mother (although this result is usually seen in buffer overruns and other such tragedies).

You shouldn't write code like this. For your family's sake.




回答2:


AFAIK there is no defined order of evaluation for the arguments of a function call, and the results might vary for each compiler. In this instance I can guess the middle argument was first evaluated, following by the first, and the third.




回答3:


As haggai_e hinted, the parameters are evalueted in this order: middle, left, right. To fully understand why these particular numbers are showing up, you have to understand how the increment works.

a++ means "do something with a, and then increment it afterwards". ++a means "increment a first, then do something with the new value".

In your particular Example, printf evaluates a++ first, reads 10 and prints it and only then increments it to 11. printf then evaluates ++a, increments it first, reads 12 and prints it out. The last variable printf evaluates is read as it is (12) and is printed without any change.

Although they are evaluated in a random order, they are displayed in the order you mentioned them. That's why you get 12 10 12 and not 10 12 12.



来源:https://stackoverflow.com/questions/1270370/printfd-d-d-n-a-a-a-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!