Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if void type function returns nothing?

Tags:

c++

c

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?

like image 310
zarcel Avatar asked Dec 02 '22 22:12

zarcel


1 Answers

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.

like image 120
Yu Hao Avatar answered Dec 22 '22 07:12

Yu Hao