Using return

suggest change

Returning 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:

  1. In a function that returns void (this does not include void *), return has no expression. The only form is return;.
  2. In a function with any other return type, a return statement must have an expression. Reaching the closing brace without returning a value is undefined behavior if the caller uses the result. main is the exception in the next item.
  3. For main only, an explicit return is not required in C99 or later. Reaching the closing } returns 0.

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. */
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents