函数参数的评估顺序
以下操作的结果将打印什么:
x=5;
printf("%d,%d,%d\n",x,x<<2,x>>2);
答案:5,20,1
我以为顺序未定义,但我在很多网站上发现了上面的面试问题。
What will be printed as the result of the operation below:
x=5;
printf("%d,%d,%d\n",x,x<<2,x>>2);
Answer: 5,20,1
I thought order is undefined yet I found above as interview question on many sites.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自 C++ 标准:
但是,如果参数为
x>>=2
和x<<=2
(这样 x 就会被修改),您的示例才会有未定义的行为。From the C++ standard:
However, your example would only have undefined behavior if the arguments were
x>>=2
andx<<=2
, such that x were being modified.位移位运算符不会修改变量的值...因此顺序并不重要。
Bit shift operators don't modify the value of the variable... so order doesn't matter.
评估顺序未指定,但这并不重要,因为您根本没有修改
x
。所以程序是明确定义的,答案也是给定的。
以下内容将具有未定义的语义:
The order of evaluation is unspecified, but it doesn't matter because you're not modifying
x
at all.So the program is well-defined, and the answer is as given.
The following would have undefined semantics:
我在 c++ 标准 中找到了答案。
第 5.2.2.8 段:
换句话说,它仅取决于编译器。
I found the answer in c++ standards.
Paragraph 5.2.2.8:
In other words, It depends on compiler only.
官方 C 规范中未定义求值顺序。
然而,出于实用性的考虑,参数通常是从右到左计算的。
在您的问题中,位移运算符不会更改 X 的值,因此评估顺序并不重要。无论是从左到右、从右到左还是从中间开始计算,您都会得到 5,20,1。
在 C 中,参数按从右到左的顺序推送到堆栈上,因此第一个参数(在本例中为 char* "%d,%d,%d")位于堆栈的顶部。参数通常(但并非总是)按照它们推送的顺序进行评估。
一个能更好地说明您所讨论内容的问题是:
官方答案是“未定义”。
实际的答案(在我尝试过的几个编译器/平台中)是“3,2,1”。
The order of evaluation is undefined in the Official C Specification.
However, as a matter of practicality, parameters are usually evaluated right-to-left.
In your problem, the bit-shift operator doesn't change the value of X, so the order of evaluation is not important. You'd get 5,20,1, whether evaluated left-to-right, right-to-left, or middle-first.
In C, parameters are pushed on to the stack in a right-to-left order, so that the 1st param (in this case, the char* "%d,%d,%d") is at the top of the stack. Parameters are usually (but not always) evaluated in the same order they are pushed.
A problem that better illustrates what you're talking about is:
The official answer is "undefined".
The practical answer, (in the several compilers/platforms I've tried), is "3, 2, 1".