这是不确定的Ç行为? [英] Is this undefined C behaviour?

查看:137
本文介绍了这是不确定的Ç行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的班级是由C编程教授问这个问题:

Our class was asked this question by the C programming prof:

您将得到code:

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

什么输出将总是产生?

What output will it always produce ?

大多数学生说未定义的行为。谁能帮我明白为什么会这样?

Most students said undefined behavior. Can anyone help me understand why it is so?

感谢您的编辑和答案,但我仍然感到困惑。

Thanks for the edit and the answers but I'm still confused.

推荐答案

的输出的可能的是在一切合理的情况下,2。在现实中,你有什么样的的未定义行为虽然。

The output is likely to be 2 in every reasonable case. In reality, what you have is undefined behavior though.

具体来说,标准说:

在previous和下一个序列点之间的对象应具有其存储的值由前pression评价修改最多一次。此外,前一个值是只读,以确定该值将被存储

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

有一个序列点的的评估参数的函数,并且所有的参数进行了评价的(但不是功能尚未调用)后的序列点的。与这两个(即当参数正在评估)存在的的序列点(除非参数是一个前pression包括一个内部,如使用&功放;&安培; || 运营商)

There is a sequence point before evaluating the arguments to a function, and a sequence point after all the arguments have been evaluated (but the function not yet called). Between those two (i.e., while the arguments are being evaluated) there is not a sequence point (unless an argument is an expression includes one internally, such as using the && || or , operator).

这意味着调用的printf 读的是以前的值的两个的决定要存储的值(即 ++ X )的的决定第二个参数的值(即 X + 1 )。这明显违反了上面引述的要求,导致不确定的行为。

That means the call to printf is reading the prior value both to determine the value being stored (i.e., the ++x) and to determine the value of the second argument (i.e., the x+1). This clearly violates the requirement quoted above, resulting in undefined behavior.

您所提供对于没有转换说明给出确实的<​​em>不的导致不确定的行为一个额外的参数的事实。如果提供的的论点,即转换说明符,的,如果(晋升)的参数类型与该转换说明的不同意你得到未定义的行为 - 但传递一个额外的参数作用的

The fact that you've provided an extra argument for which no conversion specifier is given does not result in undefined behavior. If you supply fewer arguments that conversion specifiers, or if the (promoted) type of the argument disagrees with that of the conversion specifier you get undefined behavior -- but passing an extra parameter does not.

这篇关于这是不确定的Ç行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆