GNU C的語法擴充套件(1)
表示式的宣告與定義( StatementsandDeclarationsinExpressions )

- GNUC把包含在括號中的複合語句看做是一個表示式,稱為語句表示式,它可以出現在任何允許表示式的地方,你可以在語句表示式中使用迴圈、區域性變數等,原本只能在複合語句中使用。
AcompoundstatementenclosedinparenthesesmayappearasanexpressioninGNUC.Thisallowsyoutouseloops,switches,andlocalvariableswithinanexpression.
- 複合語句的最後一個語句應該是一個表示式,它的值將成為這個語句表示式的值。
The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.(If you use some other kind of statement last with in the braces,thec onstruct has type void,and thus have novalue.
例如:該語句就是一個合法的複合語句,它的值為foo()。
({inty=foo();intz; if(y>0)z=y; elsez=-y; z;})
這種特性在巨集定義中尤為安全。(因為他們對運算元只進行一次賦值)。這裡定義了一個安全的求最小值的巨集,在標準C中,通常定義為:
Thisfeatureisespeciallyusefulinmakingmacrodefinitions"safe"(sothattheyevaluateeachoperandexactlyonce).Forexample,the"maximum"functioniscommonlydefinedasamacroinstandardCasfollows:
#definemax(a,b)((a)>(b)?(a):(b))
在這種定義下,a和b將進行兩次運算,如果他們有副作用的話將會得到錯誤的結果。在GNU C中,如果你知道運算元的型別(這裡假定為整型),你可以這樣來定義這個巨集:
Butthisdefinitioncomputeseitheraorbtwice,withbadresultsiftheoperandhassideeffects.InGNUC,ifyouknowthetypeoftheoperands(herelet'sassumeint),youcandefinethemacrosafelyasfollows:
#definemaxint(a,b)\ ({int_a=(a),_b=(b);_a>_b?_a:_b;})
在嵌入式語句中,不允許使用常量表達式,如列舉常量、位域常量和初始化靜態變數。
Embeddedstatementsarenotallowedinconstantexpressions,suchasthevalueofanenumerationconstant,thewidthofabit-field,ortheinitialvalueofastaticvariable.
當然,如果你不知道引數的具體型別,你也可以使用typeof或__auto_type運算子。
Ifyoudon'tknowthetypeoftheoperand,youcanstilldothis,butyoumustusetypeof or __auto_type.
