C ++三元运算符执行条件 [英] C++ ternary operator execution conditions

查看:212
本文介绍了C ++三元运算符执行条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定C/C ++三元运算符的执行保证.
例如,如果给我一个地址和一个布尔值,该布尔值指示该地址是否适合读取,则可以使用if/else轻松避免读取错误:

I am unsure about the guarantees of execution for the C / C++ ternary operator.
For instance if I am given an address and a boolean that tells if that address is good for reading I can easily avoid bad reads using if/else:

int foo(const bool addressGood, const int* ptr) {
    if (addressGood) { return ptr[0]; }
    else { return 0; }
}

但是三元运算符(?:)是否可以保证除非addressGood为真,否则将不访问ptr?
或者优化编译器是否可以生成在任何情况下都可以访问ptr的代码将程序崩溃),将值存储在中间寄存器中,并使用条件赋值来实现三元运算符?

However can a ternary operator (?:) guarantee that ptr won't be accessed unless addressGood is true?
Or could an optimizing compiler generate code that accesses ptr in any case (possibly crashing the program), stores the value in an intermediate register and use conditional assignment to implement the ternary operator?

int foo(const bool addressGood, const int* ptr) {
    // Not sure about ptr access conditions here.
    return (addressGood) ? ptr[0] : 0;
}

谢谢.

推荐答案

是的,该标准保证仅当addressGood为true时才能访问ptr.有关主题,请参见此答案,其中引用了标准:

Yes, the standard guarantees that ptr is only accessed if addressGood is true. See this answer on the subject, which quotes the standard:

条件表达式从右到左分组.第一个表达式在上下文中转换为bool(条款4). 要进行评估,如果为true,则条件表达式的结果为第二个表达式的值,否则为第三个表达式的值. 仅评估第二个和第三个表达式中的一个.与第一个表达式相关的每个值计算和副作用都要在与第二个或第三个表达式相关的每个值计算和副作用之前进行排序.

Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression.

(C ++ 11标准,第5.16/1段)

(C++11 standard, paragraph 5.16/1)

这篇关于C ++三元运算符执行条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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