为什么要递增运算,例如"a [i] = i ++;"?导致不确定的行为? [英] Why does increment operation like "a[i] = i++;" result in undefined behavior?

查看:92
本文介绍了为什么要递增运算,例如"a [i] = i ++;"?导致不确定的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
未定义的行为和序列点

Possible Duplicate:
Undefined Behavior and Sequence Points

#include <iostream>
using namespace std;

int main()
{
int x[3] = {};
int i=0;
x[i] = i++;
cout << x[0] << " " << x[1] << endl;
return 0;
}

键盘向我发送了以下信息:第9行:警告:"i"上的操作可能未定义 为什么操作未定义?

Codepad is giving me this: Line 9: warning: operation on 'i' may be undefined Why is the operation undefined?

推荐答案

在此处清楚地说明: C-常见问题解答

为什么此代码:a[i] = i++;不能正常工作?

Why doesn't this code: a[i] = i++; work?

子表达式i++会产生副作用-修改i'的值-这会导致不确定的行为,因为i在同一表达式的其他地方也被引用.无法知道引用是在副作用发生之前还是之后发生的-实际上,没有明显的解释可能适用;请参阅问题 3.9 . (请注意,尽管K& R中的语言表明该表达式的行为未指定,但C标准更明确地声明了该表达式的定义-请参阅问题

The subexpression i++ causes a side effect--it modifies i's value--which leads to undefined behavior since i is also referenced elsewhere in the same expression. There is no way of knowing whether the reference will happen before or after the side effect--in fact, neither obvious interpretation might hold; see question 3.9. (Note that although the language in K&R suggests that the behavior of this expression is unspecified, the C Standard makes the stronger statement that it is undefined--see question 11.33.)

相关标准报价如下:

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.

这篇关于为什么要递增运算,例如"a [i] = i ++;"?导致不确定的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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