views:

273

answers:

2

Browsing the Linux kernel sources I found some piece of code where a block of statements surrounded by parenthesis is treated as a expression a la lisp (or ML), that is, an expression which value is the value of the last statement.

For example:

int a = ({
    int i;
    int t = 1;
    for (i = 2; i<5; i++) {
        t*=i;
    }
    t;
});

I've been looking at the ANSI C grammar trying to figure out how this piece of code would fit in the parse tree, but I haven't been successful.

So, does anybody know if this behaviour is mandated by the standard or is just a peculiarity of GCC?

Update: I've tried with the flag -pedantic and the compiler now gives me a warning:

warning: ISO C forbids braced-groups within expressions
A: 

Everything is an expression in C. I didn't knew this was allowed, but it makes sense because if it wasn't, the t; sentence wouldn't be very useful.

Edit: Sorry, I forgot to answer your question. As I stated I can't say for sure if it's allowed but it makes sense to me. Besides, if it's in a not compiler-specific section of the linux code, I would bet hard that it's standard.

Jaime Pardos
Not everything is an expression, for example you cannot do (not even within a braced-group within expression) int a = if(something) foo; else bar;
fortran
True. Stupid me. +1
Jaime Pardos
+10  A: 

It's called "braced-group within expression".

It's not allowed by ANSI/ISO C nor C++ but gcc supports it.

laalto