how to explain this expression "int a=({10;});" in C language?
Asked Answered
O

2

7

During my C language practice, I face an expression and then I get it simplified as follows:

int a=({10;});

It is a legal expression since it gets past the gcc compiler. Please focus on this part: ({10;}). Is anybody able to explain it? The more detailed, the better. Thanks!

Outlying answered 16/10, 2013 at 3:27 Comment(7)
I am almost positive that's a gcc extension rather than a legal piece of C code. I'm curious to see what it is, though.Supersonics
try this also int a = [10];Clipboard
The meaning has been explained (it's a gcc extension), but it's much more clearly and portably written as int a = 10;Kythera
@GrijeshChauhan: Huh? For int a = [10];, gcc gives me error: expected expression before ‘[’ token. What did you expect it to do?Kythera
@KeithThompson Ok I am wrong I think char* s = ["grijesh"]; will work so I confused. Thanks!Clipboard
@GrijeshChauhan: No, that's also a syntax error. (You should try it before posting.)Kythera
@KeithThompson yes you are correct I should try, Now I tried and declarations int a = {1}; and char *s = {"grijesh"}; works @codepade my mistake used [] instead of {}.Clipboard
A
7

This is a statement expression. It is a gcc extension and according to the documentation 6.1 Statements and Declarations in Expressions:

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.

so for this piece of code:

int a=({10;});

according to these rules the value will be 10 which will be assigned to a.

This extension is one many gcc extensions used in the Linux kernel, although the linked article does not actually cover statement expressions, this kernel newbies FAQ entry explains some of the reasoning behind using statement expressions in the Linux kernel.

As the gcc document notes compiling with the -pedantic option will warn you when you are using a gcc extension.

Apatite answered 16/10, 2013 at 3:33 Comment(0)
T
1

It's not standard C, but an extension of GCC called statement expression. A compound statement enclosed in parentheses may appear as an expression.

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.

Back to in your example:

int a=({10;});

{10;} serves as the compound statement expression, so a has a value of 10.

Transvalue answered 16/10, 2013 at 3:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.