2012-04-13 114 views
35

通常,'?'操作者在下面的形式使用:具有空的第二參數的C條件運算符('?')

A ? B : C 

然而,在其中B = A I所看到的下列縮寫

A ? : C 

這令人驚訝地工作的情況。 (風格明智的)留下第二個參數會更好嗎?或者某些編譯器無法處理這個問題?

+0

看起來像[Groovy](http://en.wikipedia.org/wiki/Groovy_%28programming_language%29)類似的語法。 – Lion 2012-04-13 15:24:34

回答

32

語言C不允許使用(據我所知),但編譯器如gcc的快捷鍵爲?:c爲extensiona?:c的含義與a?a:c相同。

+18

這意味着...與'a'不包含副作用的警告一樣。 'a?:c'只執行一次'a',而'a?a:c'則執行兩次'a'的副作用。 – 2012-04-13 21:05:21

3

除非我犯了嚴重的錯誤,否則您使用的是編譯器擴展(猜測,gcc)。我很確定標準而不是允許您省略三元運算符的第二個操作數。

16

它是一個gcc的擴展

Conditionals with Omitted Operands

x ? : y相當於x ? x : y

+2

您鏈接的頁面與自身矛盾。一方面它說:「這個例子完全等價於'x?x:y'」,這意味着'x'被計算兩次,但另一方面最後一段聲明'x'只被計算一次,這將使它完全等價於'x || y',而不是'x? x:y' – Celada 2012-04-13 15:03:21

+1

@Celada:我想這意味着要說'x? :y'大致** ​​*相當於'x? x:y'除了'x'只在前一種情況下評估一次。 – 2012-04-13 15:05:53

+3

@Celada:'x || y'評估爲0或1,而這個算子不是這種情況。 – 2012-04-13 15:07:13

0

最好是離開的第二個參數英寸。如果B都沒有改變,你可能不記得修改上面的語句。此外,如果您將B從聲明中刪除,其他人可能難以閱讀代碼並改進它。

1

我做了一些研究網絡,acording維基百科,這種行爲是由GNU擴展C. http://en.wikipedia.org/wiki/%3F:#C

的支持所以這是非常有可能的是其他編譯器認爲這是非法的。順便說一句,這個操作符被稱爲三元條件,所以你可以瀏覽它。

編輯:

我在gcc和蘋果LLVM檢查,它工作正常。

3

我填寫了一下。

該標準使用術語有條件的運算符

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

一個條件表達式不會產生一個左值。另外; Wikipedia; Conditional

注:即: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

所以:不明智的使用。