← again tap: answer good → ↑ swipe up at the end: next
Question
What is the structure of a C function definition?
Answer
A function is <return_type> <name>(<parameters>) { <body> }; use void for "returns nothing" or "takes nothing", and it must be declared (defined or prototyped) before it's called.
<return_type> <name>(<parameter_list>)
{
<body>
}
Example - factorial:
int fact(int n)
{
if (n > 1) {
return n * fact(n-1);
} else {
return 1;
}
}
Special cases:
No return value - use void:
void print_hello(void) {
printf("Hello!\n");
// No return statement needed (or use "return;")
}
No parameters - use void (recommended) or empty:
// Explicit: takes no arguments
int get_value(void) { ... }
// C: takes unknown arguments! (legacy)
int get_value() { ... }
Return composite types:
typedef struct { int key; int value; } pair;
pair make_pair(int k, int v) {
pair p;
p.key = k;
p.value = v;
// Returns entire struct by value (copy)
return p;
}
Functions must be declared before use:
// Forward declaration (prototype)
int helper(int x);
int main(void) {
// OK - helper is declared above
return helper(5);
}
// Definition can come later
int helper(int x) {
return x * 2;
}
Question
What are function prototypes and why are they important?
Answer
A prototype is a function's signature declared ahead of its body (int f(int);), letting the compiler type-check calls and resolve forward/mutual references before it sees the definition.
// Prototype (declaration) - goes in header files
int calculate(int x, int y);
void print_result(const char *msg);
// Definition (implementation) - goes in .c files
int calculate(int x, int y) {
return x + y;
}
Why prototypes matter:
- Enable mutual recursion:
// Prototype
void foo(int n);
void bar(int n);
void foo(int n) { if (n > 0) bar(n-1); }
void bar(int n) { if (n > 0) foo(n-1); }
- Type checking:
// Without prototype, compiler might not catch:
// Would compile silently!
int result = calculate(3.14, "oops");
// With prototype, compiler checks argument types
- Separate compilation:
// math_utils.h
int add(int a, int b);
// math_utils.c
#include "math_utils.h"
int add(int a, int b) { return a + b; }
// main.c
#include "math_utils.h"
int main() { return add(1, 2); }