带有等式语句的 C++ 三元运算符 [英] C++ Ternary Operator with Equality Statement

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

问题描述

在调试别人的代码时,我遇到了如下形式的表达式:

While debugging someone else's code, I ran into an expression of the following form:

auto result = value == bool_value? result_if_bool_value: result_if_not_bool_value

我熟悉三元运算符,但我对上面语句中的双重相等运算符感到困惑.

I am familiar with ternary operators, but I am confused by the double equality operator in the above statement.

具体来说,上面用 if-else 语句编写的命令的等价物是什么?

Specifically, what is the equivalent of the above command written with if-else statements?

推荐答案

条件运算符具有较低的 优先==.因此该行被解析为:

The conditional operator has lower precedence than ==. Hence the line is parsed as:

auto result = (value == bool_value ) ? result_if_bool_value: result_if_not_bool_value

这是平常的

( condition ) ? expr_true : expr_false

一般情况下,条件运算符等价于if,但使用

In general the conditional operator is not equivalent to an if, but you get the same result with

T result;  // auto does not work here !!
if ( value == bool_value ) result = result_if_bool_value;
else result = result_if_not_bool_value;

或者如果你想保持 auto:

auto result = result_if_not_bool_value;
if (value == bool_value) result = result_if_bool_value;

尽管如此,根据所涉及的实际类型,这可能会做一些与原始类型完全不同的事情(result_if_not_bool_value 在这里独立于条件进行评估,与仅初始化相比,有一个初始化和可能的一个赋值.我可以将 result_if_not_bool_valueresult_if_bool_value 交换,但随后需要否定条件,这在所有一般情况下可能会导致不同的结果.虽然这只是超级防御,当所涉及的类型表现正常",这主要是风格问题.)

Though, depending on the actual types involved this might do something entirely different than the original (result_if_not_bool_value is here evaluated independent of the condition and there is one initialization and potentially one assignment compared to only initialization. I could swap result_if_not_bool_value with result_if_bool_value, but then the condition would need to be negated which in all generality might result in different result. Though this is all just being super defensive, when the types involved behave "normal", it is mainly a matter of style.)

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

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