带有空第二个参数的C条件运算符('?')

时间:2012-04-13 14:51:56

标签: c operators conditional ternary-operator

通常是'?'运算符以下列形式使用:

A ? B : C

然而,在B = A的情况下,我看到了以下缩写

A ? : C

这令人惊讶地奏效。是否更好地保留第二个参数(样式方式),或者某些编译器是否有机会无法处理它?<​​/ p>

6 个答案:

答案 0 :(得分:36)

语言C(据我所知)不允许这样做,但是像gcc这样的编译器的快捷方式是?:c作为extensiona?:c表示与a?a:c相同。

答案 1 :(得分:16)

它是gcc的扩展

Conditionals with Omitted Operands

x ? : y相当于x ? x : y

答案 2 :(得分:3)

除非我犯了错误,否则你正在使用编译器扩展(猜测,gcc)。我很确定标准允许你省略三元运算符的第二个操作数。

答案 3 :(得分:3)

我填写了一下。

标准使用术语 条件运算符

Syntax
  conditional-expression:
          logical-OR-expression
          logical-OR-expression ? expression : conditional-expression

条件表达式不会产生左值。另外; Wikipedia; Conditional

注意:I.e。:C ++有:
 逻辑OR表达?表达式:赋值 -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.

足部食物:

[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.

* Type qualifiers in C

所以:不明智的使用。

答案 4 :(得分:1)

我在网上进行了一些研究,根据维基百科,这种行为得到了GN的GNU扩展支持。http://en.wikipedia.org/wiki/%3F:#C

因此很可能其他编译器认为这是非法的。顺便说一下,这个运算符被称为三元条件,因此您可以浏览它。

编辑:

我检查了gcc和apple llvm,它运行正常。

答案 5 :(得分:0)

最好留下第二个参数。如果B有变化,你可能不记得修改上面的陈述。此外,如果您将B留在声明之外,其他人可能很难阅读您的代码并对其进行改进。