Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The return statement

Reference for the C return statement: returning values, structs and pointers, void functions, the special case of main, and why you must not return locals.

return ends the current function and hands control back to its caller. With an expression, the value is converted to the function's declared return type and becomes the value of the call. In a void function you write return; or simply let execution reach the closing brace.

A function may have several return statements. For non-void functions, falling off the end without returning is allowed only for main; for any other function, using the (missing) result is undefined behavior.

C
int square(int x) {
    return x * x;
}

Try it

C Values, early returns and structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Return conversions and main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
return ;
return expression ;
Form Description
return; Allowed only in functions returning void.
return expr; Evaluates expr and converts it to the return type as if by assignment. Not allowed in void functions.

Returns: to the caller. A return value may be ignored by the caller; mark important ones with [[nodiscard]].

Undefined behavior: returning the address of a local (automatic) variable gives a dangling pointer. Using the result of a non-void function that ended without a return is undefined.

Usage notes

  • Returning a pointer to a local array is the classic bug: the memory is gone when the function returns. Return heap memory (malloc), a static object, or fill a caller-supplied buffer.
  • Structs are copied on return. For small structs that is fine and often clearer than output parameters; large ones are usually passed by pointer.
  • Arrays cannot be returned. Wrap them in a struct, or return a pointer to storage that outlives the call.
  • main is special: reaching its closing brace is equivalent to return 0;. Its return value is the program exit status (EXIT_SUCCESS and EXIT_FAILURE).
  • return inside nested blocks leaves the whole function. For code that must run before leaving, use a single exit with goto.
  • Parentheses around the expression are optional: return (x); and return x; mean the same.
  • Tail calls are not guaranteed to be optimized, so deep recursion can still overflow the stack.