Return void type in C and C++

前端 未结 5 1378
我在风中等你
我在风中等你 2020-12-08 13:11

This compiles without any warnings.

Is this legal in C and C++ or does it just work in gcc and clang?

If it is legal, is it some new thing after C99?

5条回答
  •  Happy的楠姐
    2020-12-08 13:43

    C11, 6.8.6.4 "The return statement":

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

    No, you may not use an expression, even if it is of void type.

    From the foreword of the same document:

    Major changes in the second edition included:

    [...]

    • return without expression not permitted in function that returns a value (and vice versa)

    So this was a change from C89 -> C99 (the second edition of the language standard), and has been that way ever since.


    C++14, 6.6.3 "The return statement":

    A return statement with an expression of non-void type can be used only in functions returning a value [...] A return statement with an expression of type void can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller.

    Yes, you may use an expression if it is of void type (that's been valid since C++98).

提交回复
热议问题