Return value from local scope?

Found a code similar to 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; } 
  • Is the behavior of this code clear?
  • Will it really work that the result variable is loaded from 0 or -1 depending on the return value of foo(a) ?

For fun: the code was not written as it was originally - however, this is what I imagine, this innocent macro will exit the game to ...

 int foo(int a); // Forward declaration. #define BAR() { int a = dosomestuff(); foo(a); } int baz() { int result = BAR() ? 0 : -1; return result; } 
+7
c ++ c
source share
6 answers

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

The main thing is that the operator expression returns the last thing it does as the value of the expression:

The last in the compound expression must be an expression followed by a semicolon; the meaning of this subexpression serves as the meaning of the whole construction.

In your example, this will be what 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 do not know of any other compiler that supports this.

+11
source share

You will need to consult your compiler documentation. This construct is not allowed in standard C or standard C ++.

It is trivial to clear it, however, for example,

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

I do not know a single compiler that agrees with this. In addition, you will be better off:

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

This is not standard C ++.

In standard C ++ write

 bool baz() { return !foo( dosomestuff() ); } 

What is it.

+1
source share

Since this is a simple pointer without a pointer, the exact value will be returned and thus the return behavior will be determined. This block ... is really strange though, and I'm surprised there by the C compiler, which won't strangle it there.

0
source share

With C ++ 11, you can get pretty close:

 int foo(int a); // Forward declaration. int baz() { int result = []{ int a = dosomestuff(); return foo(a); }() ? 0 : -1; return result; } 
0
source share

All Articles