Background
The return operator appeared in C to explicitly terminate a function's execution and pass a result back to the calling code. In early programming languages, the ability to return values was not always present, and the return mechanism allowed for explicitly specifying the result of computations. This increased the expressiveness and safety of programs.
Issue
The main task is to correctly terminate the function and, if necessary, return a value corresponding to a defined type. Errors often occur due to returning a value of the wrong type, pointers to non-existent or local variables, or ignoring the returned value on the calling side.
Solution
Example code:
#include <stdio.h> struct Point { int x, y; }; struct Point make_point(int x, int y) { // returning a structure (copy) struct Point p = {x, y}; return p; } int* dangerous() { int num = 42; return # // dangerous: returning address of a local variable! } void do_nothing() { return; // correct for void functions } int main() { struct Point p = make_point(3, 4); printf("%d %d\n", p.x, p.y); int* ptr = dangerous(); // UB: ptr points to a destroyed area }
Key features:
Can return be used in functions without a return value (void)?
Answer: Yes, writing "return;" is allowed for void functions, but an expression (return x;) cannot be specified for a void function.
What happens when returning an array from a function?
Answer: In C, you cannot return an array directly. You can only return a pointer (for example, to a static array), but it is more common to return a pointer and size or use a dynamically allocated array.
int* make_arr() { static int arr[5] = {1,2,3,4,5}; return arr; // static array lives after function exit }
Why is it dangerous to return a pointer to a local variable?
Answer: Once the function exits, the memory for the local variable is freed (stack area). Using the returned pointer leads to undefined behavior.
Negative Case
A function returns a pointer to a local variable, causing the caller to receive "garbage", unpredictable behavior, and rare floating bugs.
Pros:
Cons:
Positive Case
Using a returned structure (copied by value) or returning a pointer to static/dynamic memory:
Pros:
Cons: