简体   繁体   中英

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?

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.

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 )

Overlooking the fact that this code has undefined behaviour because it is missing a value for the return statement....

when run on a CPU that actually has defined bit registers, and associated compiler, this returned boolean will be in the carry flag.

when run on most modern CPUs, which do not actually have defined bit registers, and associated compiler, it will return an int value. however a modern compiler (with all warnings enabled) will not compile the file, but will raise a warning about invalid return type (or similar statement)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM