基于短路逻辑操作条件执行 [英] Conditional execution based on short-circuit logical operation
问题描述
由于逻辑运算符的计算&放大器;&安培;
和 ||
被定义为短路,我假设code以下两件是等价的:
As the evaluation of logical operators &&
and ||
are defined as "short circuit", I am assuming the following two pieces of code are equivalent:
p = c || do_something();
和
if (c) {
p = true;
}
else {
p = do_something();
}
给 P
和 C
是布尔
,和 do_something()
是返回一个函数布尔
和可能有副作用。根据C标准,人们可以依靠假设的片段是相同的?特别是具有第一片段,难道是承诺,如果 C
为真,功能将不被执行,它没有副作用会发生?
given p
and c
are bool
, and do_something()
is a function returning bool
and possibly having side effects. According to the C standard, can one rely on the assumption the snippets are equivalent? In particular, having the first snippet, is it promised that if c
is true, the function won't be executed, and no side effects of it will take place?
推荐答案
一些搜索后,我会回答我的问题我自己参考的标准:
该 C99标准,部分 6.5 0.14逻辑或运营商的说明:
After some search I will answer my question myself referencing the standard: The C99 standard, section 6.5.14 Logical OR operator is stating:
不同的是按位|操作者,在||运营商保证
左到右的评价;有一个序列点之后的
第一个操作数的评价。如果第一个操作数比较不等
为0,第二个操作数不评估
Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.
和类似的部分约&放大器;&安培;
。
因此,答案是肯定的,code可以安全地认为是等效的。
And a similar section about &&
.
So the answer is yes, the code can be safely considered equivalent.
这篇关于基于短路逻辑操作条件执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!