Can a void-returning function g return f(); when f returns void?

后端 未结 3 1196
不知归路
不知归路 2020-12-30 23:26

Consider the following snippet:

void f(void);

void g(…)
{
  …
  return f();
  …
}

Is this return f(); valid according to C11?

相关标签:
3条回答
  • 2020-12-31 00:06

    It clearly states A return statement without an expression shall only appear in a function whose return type is void, try and execute this:

    void g()
    {
        return; // does not return any expression at all
    }
    void f()
    {
        return g();
    }
    
    
    int main(void) {
        f();
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-31 00:14

    Anything after return is an expression.

    6.8.6:1 Jump statements

    Syntax  
    
       ...
       return expressionopt; 
    

    And standard says that:

    A return statement with an expression shall not appear in a function whose return type is void. ....

    f() is also an expression here. The compiler should raise a warning

    [Warning] ISO C forbids 'return' with expression, in function returning void [-pedantic]
    
    0 讨论(0)
  • 2020-12-31 00:17

    This clearly is a constraint violation, in particular in view of

    6.3.2.2 void: The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way,

    That means that the incomplete type void is a dead end that cannot be reused for any purpose whatsoever.

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