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; /* More than one argument after the program name. */
}
/* Do stuff. */
return EXIT_SUCCESS;
}
Additional notes:
- In a function that returns
void(this does not includevoid *),returnhas no expression. The only form isreturn;. - In a function with any other return type, a
returnstatement must have an expression. Reaching the closing brace without returning a value is undefined behavior if the caller uses the result.mainis the exception in the next item. - For
mainonly, an explicitreturnis not required in C99 or later. Reaching the closing}returns0.
Returning nothing
Returning from a void function
#include <stdio.h>
void log_message(const char * message_to_log)
{
if (NULL == message_to_log)
{
return; /* Nothing to log. Skip the rest of the function. */
}
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