关于短路评价安全性问题 [英] Safety concerns about short circuit evaluation

查看:110
本文介绍了关于短路评价安全性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/628526/is-short-circuiting-boolean-operators-mandated-in-c-c-and-evaluation-order\">Is短路在C / C ++授权布尔运算符?和评估顺序?

据我所知短路评价是指一个布尔值前pression只计算到,我们可以保证其结果的地步。

AFAIK Short circuit evaluation means that a boolean expression is evaluated only up to the point that we can guarantee its outcome.

这是Perl,我们可以写东西像一个常见的​​成语:
(is_ok()确定按钮返回非零值)

This is a common idiom in perl where we can write things like: (is_ok() returns non-zero value on "OK")

is_ok() || die "It's not OK!!\n";

而不是

if ( ! is_ok() ) {
    die "It's not OK!!\n";
}

这不仅是因为作品评价的顺序总是左到右,这保证了最右边的语句只执行,如果第一条语句如果没有假。

This only works because the order of evaluation is always left-to right and that guarantees that the rightmost statement is only executed if the first statement if not "false".

在C I可以做一些类似呈三角:

In C I can do something simillar like:

struct foo {
    int some_flag;
} *ptr = 0;

/* do some work that may change value of ptr */
if ( 0!=ptr && ptr->some_flag ) {
    /* do something */
}

是否可以安全使用这种成语?

Is it safe to use this kind of idiom?

或者是有任何机会,编译器可能会产生code,其值 ptr-&GT; some_flag 确保PTR不是零指针之前? (我假设,如果它是非空它指向一些有效的内存区域)。

Or is there any chance that the compiler may generate code that evaluates ptr->some_flag before making sure that ptr is not a zero pointer? (I am assuming that if it is non-null it points to some valid memory region).

本语法方便使用,因为它节省不失可读性(反正在我看来)打字。但是我不知道这是否是完全安全这就是为什么我想了解更多关于这个。

This syntax is convenient to use because it saves typing without losing readability (in my opinion anyway). However I'm not sure if it is entirely safe which is why I'd like to learn more on this.

注意:如果编译器有这个效果,我用gcc 4.x版

NB: If the compiler has an effect on this, I'm using gcc 4.x

推荐答案

短路运算符( || &放的评价顺序; &安培; )由标准保证被左到右(否则他们将失去其效用的一部分)

The evaluation order of short-circuit operators (|| and &&) is guaranteed by the standard to be left to right (otherwise they would lose part of their usefulness).

§6.5.13¶4

不同的是按位二进制&安培; 运算符,&放大器;&安培; 运营商保证左到右评价;
  还有就是第一个操作数的评估后的序列点。如果第一操作数
     比较等于 0 ,第二个操作数不计算。

Unlike the bitwise binary & 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 equal to 0, the second operand is not evaluated.

§6.5.14¶4

不同的是按位 | 运算符, || 运营商保证左到右的评价;有
  第一个操作数的评估后的序列点。如果第一个操作数进行比较
     不等于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.

这篇关于关于短路评价安全性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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