Function Interface & Return Values
A function is C's unit of reuse and its unit of testing. A good interface hides the implementation and makes the contract obvious.
In plain English
A function is a small machine. You put values in, it does a job, and it may hand a value back.
Definition, prototype, and interface
A function definition has a return type, a name, a parameter list, and a body. A declaration, or prototype, tells the compiler the signature before the definition appears. The interface is the signature plus the contract: what the arguments mean, what the return value represents, and what the function is allowed to change. Put prototypes in a header when several source files share the function.
/* prototype */
int add(int a, int b);
int main(void) {
printf("%d\n", add(2, 3));
return 0;
}
int add(int a, int b) {
return a + b;
}Return values, local variables, and void
return ends the function and sends a value back to the caller. A function declared void returns nothing. Local variables live in the function's stack frame and disappear when it returns, so never return a pointer to a local variable. Modern C requires an explicit return type; older C assumed int when one was omitted.
void print_banner(const char *text) {
printf("== %s ==\n", text);
}
int square(int x) {
int result = x * x;
return result;
}Kinds of subprograms and return mechanics
C supports user-defined functions, library functions, iterative functions, recursive functions, and functions that either return a value or return void. At the machine level, a small return value usually travels back in a register. A large structure returned by value may use a hidden pointer supplied by the caller. That mechanism is part of the platform ABI, not something the C source language guarantees.
Key takeaways
- A prototype lets the compiler check calls before the definition.
- A function interface is a contract, not just a signature.
- C supports user-defined, library, iterative, and recursive subprograms.
- A function cannot safely return a pointer to a local.
- void means the function returns no value.
Common pitfalls
- Returning the address of a local variable.
- Mismatching the prototype and the definition.
- Ignoring the return value of a function that reports errors.
- Assuming a large struct return is free; it may involve a hidden copy.
Key focus
- Know the difference between a declaration and a definition.
- Expect questions on prototypes, default return types, and void.
Quick check
1. What is the purpose of a function prototype?
2. What does a void return type mean?