没有中间表达式的三元运算符

Ternary operator without the middle expression

我最近意识到您可以在 GCC 和 clang 中使用三元运算符而无需中间(?:? : 有效),它会将第一个表达式插入中间:

// outputs 2
cout << (2 ?: 4);
// outputs 3
cout << (0 ?  : 3);

这在标准中的什么位置?我看了看,什么都没看到。

它根本不在标准中

您观察到的是一个 GCC 扩展:https://gcc.gnu.org/onlinedocs/gcc/Conditionals.html

如果省略它,它的值取自上下文转换为 bool 之前的第一个操作数。
扩展价值在于不重复 side-effects 和减少 source-codes 大小。