c - C中的序列点和副作用

标签 c undefined-behavior sequence-points

在此C-FAQ它是关于 sequence point 的;

The Standard states that;
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 accessed only to determine the value to be stored.

在例子中

i = i++;
a[i] = i++;

从声明的第一句可以清楚地看出,这些示例导致了未定义的行为
在解释声明的第二句时,据说;

second sentence says: if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written. This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification. For example, the old standby

 i = i + 1 

is allowed, because the access of i is used to determine i's final value. The example

a[i] = i++

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define.

我的问题是;
1.如果在完整表达式中写入一个对象,则在同一表达式中对其进行的任何和所有访问都必须直接参与要写入的值的计算,这是什么意思。

2. 例子 a[i] = i++ 是什么意思 是不允许的,因为对 i 的访问之一(a[i] 中的访问)与最终存储在 i 中的值无关(在 i++ 中发生)
有人可以用一些简单的方式解释一下吗?

最佳答案

My question are; 1.What does it mean by, if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.?

使用像i++ 这样的子表达式,i 被写入。而且,赋值是一个表达式,所以在i = 2中,i被写入。 a = b 是一个表达式可能不是很明显,但它确实是。这就是为什么您可以执行诸如 a = b = c 之类的事情,这是好的,而 if (a = b) 则不太好。

所以它的意思是,如果你写入 i,使用 =,或者前增量或后增量,那么对 i 的任何访问都必须作为一部分i 的新值的计算。然而,这一点很重要,唯一涉及前后增量计算的是 i 语句开头的值。

2.what does it mean by, The example a[i] = i++ is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++)

正是它所说的。当您在 a[i] 中访问 i 时,它不是 i++ 产生的 i 新值计算的一部分

Could someone explain it in some easy way?

简单方法:不要在表达式中使用前置或后置增量。始终在语句中单独使用它们。如果您确实必须这样做,请不要在整个语句 的其他任何地方使用相同的变量。

关于c - C中的序列点和副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17473706/

相关文章:

c++ - strcpy 中的段错误

c - 为什么我的空字符数组以长度 6 开头?

c++出现奇怪的段错误

c# - 相同的代码,C# 和 C++ 中的不同输出

c - 使用 scanf 时 getchar 不会停止

c - Qt C 错误重复符号 _function_names in juicy_lucy.o 和 main.o for architectures x86_64

这个 C 循环可以进一步优化吗?

c - scanf 段错误和 while 循环内的各种其他异常

c - 这个程序有任何序列点问题吗?

c - C语言的求值顺序