通常是“?” 运算符以下列形式使用:
A ? B : C
但是,在 B = AI 的情况下,会看到以下缩写
A ? : C
这出人意料地有效。将第二个参数留在(风格方面)更好,还是某些编译器无法处理这个问题?
通常是“?” 运算符以下列形式使用:
A ? B : C
但是,在 B = AI 的情况下,会看到以下缩写
A ? : C
这出人意料地有效。将第二个参数留在(风格方面)更好,还是某些编译器无法处理这个问题?
语言 C 不允许这样做(据我所知),但 gcc 等编译器具有快捷方式 a?:c 作为扩展名。
a?:c
意思相同a?a:c
。
除非我大错特错,否则您使用的是编译器扩展(猜测是 gcc)。我很确定标准不允许您省略三元运算符的第二个操作数。
我稍微填一下。
该标准使用术语条件运算符。
语法 条件表达式: 逻辑或表达式 logical-OR-expression ? expression : conditional-expression
A conditional expression does not yield an lvalue. Also; Wikipedia; Conditional
Note: I.e.: C++ has:
logical-OR-expression ? expression : assignment-expression
Constraints: * The first operand shall have scalar type[1]. * One of the following shall hold for the second and third operands: — both operands have arithmetic type[2]; — both operands have the same structure[3] or union type[4]; — both operands have void type[5]; — both operands are pointers to qualified or unqualified[6] versions of compatible types[7]; — one operand is a pointer and the other is a null pointer constant[8]; or — one operand is a pointer to an object or incomplete type[9] and the other is a pointer to a qualified or unqualified version of void.
Foot food:
[1] Scalar type : Arithmetic types and pointer types. [2] Arithmetic type : Integer and floating types. [3] Structure type : A sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type. [4] Union type : An overlapping nonempty set of member objects, each of which has an optionally specified name and possibly distinct type. [5] Void type : An empty set of values; it is an incomplete type that cannot be completed. [6] Qualified type : 1998 (const and volatile), 1999 (restrict), respectively 2011 (_Atomic). * [7] Compatible type : Their types are the same. [8] Null ptr. const.: NULL; implementation-defined null pointer constant. [9] Incomplete type : Types that describe objects but lack information needed to determine their sizes.
So: Not wise to use.
我在网上做了一些研究,根据维基百科,这种行为得到了 C 的 GNU 扩展的支持。http://en.wikipedia.org/wiki/%3F:#C
所以其他编译器很可能认为这是非法的。顺便说一句,这个运算符被称为三元条件,因此您可以浏览它。
编辑:
我检查了 gcc 和 apple llvm,它工作正常。
最好保留第二个参数。如果 B 发生变化,您可能不记得修改上面的语句。此外,如果您将 B 排除在语句之外,其他人可能难以阅读您的代码并对其进行改进。