[英]Is post-increment operator guaranteed to run instantly?
Let's say I have the following code:假设我有以下代码:
int i = 0;
func(i++, i++);
The increment is happening right after returning the value?返回值后立即发生增量? Is it guaranteed that the first argument will be 0, and the second argument will be 1?
是否保证第一个参数为 0,第二个参数为 1?
This code is broken for two reasons:这段代码被破坏有两个原因:
Undefined behavior and sequence points 未定义的行为和序列点
Why are these constructs (using ++) undefined behavior? 为什么这些构造(使用 ++)是未定义的行为?
No, your code is erroneous.不,你的代码是错误的。 There is no sequence point between the evaluation of function arguments, and two operations with side effect on the same object are only allowed if they are separated by a sequence point.
函数参数的求值之间没有序列点,两个对同一个对象有副作用的操作只有在它们被序列点分隔时才被允许。
Your concept of "run instantly" doesn't exist in C. Closest comes perhaps the idea of sequenced operations, where the above mentioned sequence points forcibly separate the execution of two statements or expressions. C 中不存在“立即运行”的概念。最接近的可能是顺序操作的想法,其中上述顺序点强制分隔两个语句或表达式的执行。
Is it guaranteed that the first argument will be 0, and the second argument will be 1?
是否保证第一个参数为 0,第二个参数为 1?
No. Its undefined behavior.不。它的未定义行为。 The order of evaluation of function arguments are not guaranteed from left to right or right to left, ie order of evaluation is unspecified and therefore side effect on
i
is unsequenced.不能保证函数参数的求值顺序是从左到右或从右到左,即求值顺序是未指定的,因此对
i
副作用是无序的。
If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined [...]
如果相对于对同一标量对象的不同副作用或使用同一标量对象的值进行的值计算,标量对象的副作用是未排序的,则行为未定义 [...]
When you write i++
, you are asking for two things to happen:当您编写
i++
,您要求发生两件事:
i
and add one to iti
的值并加一i
i
Now, what you have to understand is that although #1 happens immediately, #2 does not .现在,您必须了解的是,尽管 #1 会立即发生,但#2 不会。 The right way to think about #2 is that it happens "sometime later".
考虑#2 的正确方式是它发生在“稍后”。 That's why we can't say what
func(i++, i++);
这就是为什么我们不能说
func(i++, i++);
does.做。 We have no way of knowing whether one of the
i++
's stores its result back into i
before or after the second i++
happens.我们无法知道
i++
的一个是在第二个i++
发生之前还是之后将其结果存储回i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.