C语言中的此代码是否属于“未定义行为"类别? [英] Does this code in C fall into the Undefined Behavior category?
本文介绍了C语言中的此代码是否属于“未定义行为"类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a
是一个数组,foo
是一个函数,而i
是一个int
.
a
is an array, foo
is a function, and i
is an int
.
a[++i] = foo(a[i-1], a[i]);
上面的代码是否具有未定义的行为?
保证数组索引++i
,i-1
和i
在数组范围内.
The array indices ++i
, i-1
and i
, are guaranteed to be in the array range.
推荐答案
行为未定义,但这不是因为同一对象在两个序列点之间两次修改两次,而是因为UB,因为对i
的副作用相对于使用i
的a[i-1]
和a[i]
的值计算,它是不连续的.
The behavior is undefined, but it's not because of the modification of the same object twice between two sequence points but it is UB because the side effect on i
is unsequnced relative to the value computation of a[i-1]
and a[i]
using i
.
§6.5-p(2):
如果相对于相同标量对象的副作用不同,或者使用相同标量对象的值进行值计算,则相对于相同标量对象的副作用没有顺序未定义.如果一个表达式的子表达式有多个允许的排序,则如果在任何排序中都出现这种无序的副作用,则行为是不确定的. 84)
例如表达式
a[i++] = i;
调用未定义的行为.
a[++i] = foo(a[i-1], a[i]);
这篇关于C语言中的此代码是否属于“未定义行为"类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文