Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from local scope?

Tags:

c++

c

Bumped into some code like this in our code base... which made me worried.

int foo(int a); // Forward declaration.

int baz() {
    int result = {
         int a = dosomestuff();
         foo(a);
    } ? 0 : -1;
    return result;
}
  1. Is the behavior of this code well-defined?
  2. Will it really work, that result variable gets loaded with 0 or -1 depending on the return value of foo(a)?

For interest: The code was not written like that originally - however, it is what I imagine this innocent-looking macro will roll out to...

int foo(int a); // Forward declaration.

#define BAR()  { int a = dosomestuff(); foo(a); }

int baz() {
    int result = BAR() ? 0 : -1;
    return result;
}
like image 305
Johan Kotlinski Avatar asked Dec 08 '10 18:12

Johan Kotlinski


1 Answers

This is a GCC extension to C called 'statement expressions': http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html

The key thing is that a statement expression returns the last thing it does as the value of the 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.

In your example, that would be whatever foo(a) returns.

However the block must be enclosed in parens for GCC to accept the syntax.

int foo(); // Forward declaration.

int baz() {
    int result = ({
         int a = dosomestuff();
         foo(a);
    }) ? 0 : -1;
    return result;
}

I'm unaware of any other compiler that supports this.

like image 67
Michael Burr Avatar answered Sep 21 '22 11:09

Michael Burr