gpt4 book ai didi

C++ 三元运算符执行条件

转载 作者:IT王子 更新时间:2023-10-28 23:34:04 25 4
gpt4 key购买 nike

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

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

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

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

谢谢。

最佳答案

是的,标准保证 ptr 只有在 addressGood 为真时才被访问。见 this answer关于这个主题,它引用了标准:

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++ 三元运算符执行条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17665519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com