Is this undefined behavior or implementation defined?

早过忘川 提交于 2019-12-12 05:27:29

问题


Is the following undefined or implementation-defined:

 int x = 0;
 printf("%d%d", ++x, x);

The order of evaluating arguments is unspecified, so:

  • if ++x is evaluated first, this prints 11.
  • if x is evaluated first, it prints 10.

回答1:


printf("%d%d", ++x, x);

This is clearly undefined behavior in C++.

(C++11, 1.9p15) "If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."

Same for C (emphasis mine):

(C99, 6.5.p2) "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73"

Note that C11 has now a similar wording as in C++11:

(C11, 6.5p2) "If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined."



来源:https://stackoverflow.com/questions/11657100/is-this-undefined-behavior-or-implementation-defined

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