gpt4 book ai didi

c++ - 这是在序列点之间对同一对象的多次访问定义明确的行为吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:33 26 4
gpt4 key购买 nike

是否允许多次访问?

#include <iostream>

int main()
{
int A[1];
A[0] = 0;
A[A[0]] = 1;
std::cout << A[0];
}

引用以下段落...

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. 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[0] 的旧值,它应该是未定义的行为,对吧?

最佳答案

是的,它是有效的。

首先,在作业的 LHS 上读取 A[0] 是完全有效且定义明确的,原因与此相同:

int x = 42;
x = x + 1;

在执行赋值之前,必须对两个操作数求值。

其次,孤立地评估 A[A[0]] 非常好:

[C++11: 1.9/15]: [..] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. [..]

在 C++03 中,我能找到的最接近相关的措辞是关于赋值的以下内容(尽管在 gaff 中有诸如 a = a + x 之类的构造示例):

[C++03: 5.17/8]: If the value being stored in an object is accessed from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have the same type, otherwise the behavior is undefined.

关于c++ - 这是在序列点之间对同一对象的多次访问定义明确的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29215437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com