Return value from local scope?

后端 未结 6 1011
终归单人心
终归单人心 2021-01-05 11:06

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

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

int baz() {
    int result = {
         i         


        
相关标签:
6条回答
  • 2021-01-05 11:21

    You'd have to consult your compiler documentation. This construct is not allowed in standard C or standard C++.

    It's trivial to clean this up however, e.g.

    int baz()
    {
        int result;
        {
             int a = dosomestuff();
             result = foo(a)? 0: -1;
        }
        return result;
    }
    
    0 讨论(0)
  • 2021-01-05 11:22

    I do not know of a single compiler that will accept that. Additionally, you'd be better off doing this:

    int foo();
    int dosomestuff();
    
    int baz()
    {
       int result = foo(dosomestuff()) ? 0 : -1;
       return result;
    }
    
    0 讨论(0)
  • 2021-01-05 11:23

    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 讨论(0)
  • 2021-01-05 11:25

    Because it's a non-pointer simple type, the exact value will be returned and so the return behavior is defined. That block is... really strange though, and I'm surprised there's a C compiler that won't choke on it out there.

    0 讨论(0)
  • 2021-01-05 11:26

    It's not standard C++.

    In standard C++, write

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

    That's it.

    0 讨论(0)
  • 2021-01-05 11:38

    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.

    0 讨论(0)
提交回复
热议问题