In what versions of C is a block inside parenthesis used to return a value valid?

后端 未结 3 732
忘掉有多难
忘掉有多难 2020-11-28 14:11

If I do:

int j = ({int x = 7; x+3;});

In i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646) gcc it compiles just fine. The

3条回答
  •  囚心锁ツ
    2020-11-28 15:11

    If you remove the parenthesis it doesn't compile.

    Without the parentheses, the compiler will treat this as an aggregate initialization block and will fail when it sees the int keyword. You cannot have keywords in initializer blocks.

    6.7.8 Initialization

    11 The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

    6.2.5 Types

    21 Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.


    Can I expect this to work in most c compilers?

    No. Looks like a non-standard GNU extension.

    Additionally, what is the name for this construct?

    I wonder if there is any. Actually, this is similar to what macros typically do.

提交回复
热议问题