What's coming back; in C function return type boolean?

Say the function in C of boolean return type (boolean can be implemented as enumerating 0 and 1 or in some other way, but it doesn't matter):

boolean foo ()
{
  //do something

  return;
}

      

What does it mean? does it return FALSE? or does it just exit the function without any return? what will the function expecting to return from foo expect?

+3


source to share


3 answers


This behavior is undefined, a return statement without an expression should only be used in a function whose return type is invalid. This is described in the draft C99 project 6.8.6.4

return statement:

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

Interestingly, this is a default error when used clang

, but gcc

without any flags, it seems to allow this code without warning. For gcc

using -std=c99

this turns it into a warning and using the flag -pedantic-errors

makes it an error.



A good set of flags to use when compiling C programs with gcc

or clang

would be:

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

Tuning -std

into the appropriate standard you are targeting.

+7


source


According to standard (draft) C99, section 6.8.6.4 The return statement

(clause 1):

A return statement with an expression must not appear in a function whose return type is invalid. A return statement without an expression should only appear in a function whose return type is invalid.

Thus, the code will be invalid.

Compiling using GCC with -Wall throws an error:



warning: 'return' without value, in non-void function [-Wreturn-type]

Although it compiles when -Wall is not used and returns 1 (true), but I assume GCC is good (?).

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

+3


source


By changing the fact that this code has undefined behavior because it lacks meaning for the return ... statement ...

when run on a CPU that actually has certain bit registers, and the compiler associated with it, this boolean return will be in the carry flag.

when run on most modern processors that do not actually have specific bit registers and an associated compiler, it will return an int. however a modern compiler (with all warnings included) will not compile the file, but will raise an invalid return type warning (or similar statement)

0


source







All Articles