Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does return; in a C function of boolean return type return?

Say a function in C of boolean return type (boolean may be implemented as an enum of 0 and 1 or some other way, but that is not important):

boolean foo ()
{
  //do something

  return;
}

What does this return? does it return FALSE? or does it just exit from the function without any return? what will a function expecting a return from foo receive?

like image 516
Vivek Vijayan Avatar asked Jul 20 '26 09:07

Vivek Vijayan


2 Answers

This is undefined behavior, a return statement without an expression shall only be used in a function whose return type is void. This is covered in the draft C99 standard section 6.8.6.4 The return statement:

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

Interestingly this is an error by default when using clang but gcc without any flags seems to allow this code without even a warning. For gcc using the -std=c99 turns this into a warning and using the -pedantic-errors flag makes it an error.

A good set of flags to get used to using when compiling C programs using either gcc or clang would be the following:

-std=c99 -Wall -Wextra -Wconversion -pedantic

Adjusting the -std to the appropriate standard you are targeting.

like image 116
Shafik Yaghmour Avatar answered Jul 22 '26 01:07

Shafik Yaghmour


According to the (draft) C99 standard, section 6.8.6.4 The return statement (paragraph 1):

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.

So the code would be invalid.

Compiling this using GCC with -Wall throws an error:

warning: 'return' with no value, in function returning non-void [-Wreturn-type]

Although it compiles when not using -Wall and returns 1 (true), but I'm guessing this is GCC being nice (?).

(taken from WG14/N1256 Committee Draft — Septermber 7, 2007 ISO/IEC 9899:TC3)

like image 33
jpw Avatar answered Jul 21 '26 23:07

jpw