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.
int square(int x) { return x * x; }
Try it
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.
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
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), astaticobject, 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.
mainis special: reaching its closing brace is equivalent toreturn 0;. Its return value is the program exit status (EXIT_SUCCESS and EXIT_FAILURE).returninside nested blocks leaves the whole function. For code that must run before leaving, use a single exit withgoto.- Parentheses around the expression are optional:
return (x);andreturn x;mean the same. - Tail calls are not guaranteed to be optimized, so deep recursion can still overflow the stack.
Related
goto,main(), attributes, return values- Lessons: Parameters and return values, Functions