Using return
suggest changeReturning a value
One commonly used case: returning from main()
#include <stdlib.h> /* for EXIT_xxx macros */
int main(int argc, char ** argv)
{
if (2 < argc)
{
return EXIT_FAILURE; /* The code expects one argument:
leave immediately skipping the rest of the function's code */
}
/* Do stuff. */
return EXIT_SUCCESS;
}
Additional notes:
- For a function having a return type as
void
(not includingvoid *
or related types), thereturn
statement should not have any associated expression; i.e, the only allowed return statement would bereturn;
. - For a function having a non-
void
return type, thereturn
statement shall not appear without an expression. - For
main()
(and only formain()
), an explicitreturn
statement is not required (in C99 or later). If the execution reaches the terminating\}
, an implicit value of0
is returned. Some people think omitting thisreturn
is bad practice; others actively suggest leaving it out.
Returning nothing
Returning from a void
function
void log(const char * message_to_log)
{
if (NULL == message_to_log)
{
return; /* Nothing to log, go home NOW, skip the logging. */
}
fprintf(stderr, "%s:%d %s\n", __FILE__, _LINE__, message_to_log);
return; /* Optional, as this function does not return a value. */
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents