4

Let's say we have function like this

void test() {return;}

Is is it correct C code? I just tested it in mingw and compiler says nothing, the same for

void test() {return 1;}

So I guess I have really outdated compiler.

What should happen in given cases in both C/C++?

EDIT:

The return 1; gives me a warning. Does this mean return; is correct?

4

3 回答 3

17

C++11(ISO/IEC 14882:2011) §6.6.3 The return statement

A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor, or a destructor. A return statement with an expression of non-void type can be used only in functions returning a value

C11(ISO/IEC 9899:201x) §6.8.6.4 The return statement

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

However, C89/C90 only constraints on half of it:

C89/C90(ISO/IEC 9899:1990) §3.6.6.4 The return statement

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

In the C11 Forward section, it lists all the major changes in the third(i.e, C11) and second edition(i.e, C99). The last one of them is:

Major changes in the second edition included:

...

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

This means that the constraint change of function return type is changed since C99.

于 2013-07-08T15:21:42.987 回答
0

Void returns nothing so its obvious compiler won't do anything. If you want to return a value you must define the type whether int ,pointer node etc. etc.

于 2013-07-08T15:27:21.540 回答
0

The return statement without an expression is the correct way to return from a function that returns void.

But, if you want to provide an expression in the return statement, then you should consider:

return (void)(expr);

Here, the expr is any expression that you want to include to have side-effects. As a suggestion, if you want to place a statement for its side-effect, then you should place it before the return statement as :

expr;
return;
于 2013-07-09T03:31:00.627 回答