- What a function prototype is and why it matters
- Declaration vs definition — what each one does
- Call by value vs call by reference
- How recursion works and when to avoid it
- Function pointers and callback patterns
- The
static,inline, andvoidkeywords - Variable arguments and why C has no overloading
This page answers 20 of the most-asked function questions from C interviews and exams. It starts with prototypes and the declaration-vs-definition distinction, then covers parameter passing, recursion, function pointers, and callbacks. Each answer is in plain English with a small code example you can use in interviews or in your own code. If you're preparing for a technical interview, pay close attention to Q1 (prototypes), Q6 (call by value vs reference), and Q12 (function pointers) — all come up again and again.
Prototypes, declarations, definitions
Q1. What is a function prototype in C, and why is it necessary?
Answer: A prototype tells the compiler the function's return type, name, and parameter types — before the function is defined.
A prototype is the function header followed by a semicolon. It says "this function exists, here's how to call it":
int add(int a, int b); /* prototype */
int main(void) {
int s = add(2, 3); /* compiler checks args here */
return 0;
}
int add(int a, int b) { /* definition */
return a + b;
}
Why it's necessary:
- Type checking: the compiler verifies each call — the number and type of arguments — against the prototype.
- Return type check: if the function returns a
doubleand you assign it to anint, the compiler warns you. - Order independence: you can call a function before its definition, as long as the prototype appears first.
Without a prototype, C89 assumes the function returns int and takes any number of arguments. That's a bug waiting to happen — modern C compilers warn about missing prototypes with -Wmissing-prototypes.
Full tutorial: Function Declaration in C — syntax and examples
Q2. What is the difference between a function declaration and a function definition in C?
Answer: A declaration tells the compiler the function exists; a definition provides the body that actually runs.
A declaration (prototype) gives the compiler the signature — return type, name, and parameters. No memory is reserved, no code is generated:
int add(int a, int b); /* declaration */
A definition provides the body — the statements that run when the function is called:
int add(int a, int b) { /* definition */
return a + b;
}
Rules to remember:
- You can declare a function many times (headers do this).
- You can define a function only once per program (otherwise: "multiple definition" error at link time).
- The prototype in a header file lets every source file that includes the header call the function safely.
Full tutorial: Function Definition in C
Q3. What happens if a function is called before it is declared or defined?
Answer: In C89 the compiler assumes the function returns int and takes unspecified arguments. In C99 and later, this is an error.
In older C compilers, calling an undeclared function triggered "implicit declaration" — the compiler guessed int func() and hoped for the best. If the real function returned a double or a pointer, the caller would read garbage.
Modern C (C99 and later) requires a declaration before any call. GCC and Clang will compile with a warning by default, but -Werror=implicit-function-declaration turns it into a hard error — which is the correct behaviour.
The fix is simple: put prototypes in a header file and #include it in every source file that calls the function.
Passing arguments and return values
Q4. How do you pass arguments to a function in C?
Answer: By value (default — a copy is made) or by pointer (the caller's variable can be modified).
Pass by value — the function receives a copy of the argument. The original is untouched:
void change(int x) {
x = 100; /* only the copy changes */
}
int main(void) {
int n = 5;
change(n); /* n is still 5 */
return 0;
}
Pass by pointer — the function receives the address, so it can modify the caller's variable:
void change(int *p) {
*p = 100; /* modifies the caller's variable */
}
int main(void) {
int n = 5;
change(&n); /* n becomes 100 */
return 0;
}
Strictly speaking, C only has pass by value. What people call "pass by reference" in C is pass by value of a pointer. The effect is that the callee can modify the caller's data — that's what the term means in practice.
Full tutorial: User-Defined Functions in C
Q5. What is the significance of the return statement in a function?
Answer: It ends the function immediately and (optionally) sends a value back to the caller.
int square(int x) {
return x * x; /* returns x², ends the function */
}
void print_msg(void) {
printf("hi\n");
return; /* valid — just exits */
}
Points to remember:
- You can have multiple
returnstatements. Only one is reached per call. - In a non-
voidfunction, every path must return a value. If it falls off the end without returning, the behaviour is undefined. return;in avoidfunction is fine — it just exits.- Any code after
returnin the same block is dead code; the compiler may warn.
Q6. What is the difference between call by value and call by reference?
Answer: Call by value copies the argument; call by reference passes the address so the function can change the original.
Side-by-side:
- Call by value — the function gets a copy in its own memory. Changes inside the function do not affect the caller. The original data is safe. This is C's default.
- Call by reference — the function gets the address. Changes inside the function are visible to the caller. Useful for returning multiple values, or for large structs where copying would be expensive. In C, this is done with pointers.
When to use which:
/* pass by value — simple ints, chars, small structs */ int add(int a, int b); /* pass by pointer — need to modify caller's data, or copy is expensive */ void swap(int *a, int *b); void fill_array(int *arr, int n);
Rule of thumb: if the function reads the value and doesn't modify it, pass by value (or a const pointer for structs). If it needs to modify the caller's data, pass a pointer.
Full tutorial: Scope, Visibility, and Lifetime of Variables
Q7. Can a function return multiple values in C? If not, how can you achieve a similar effect?
Answer: Not directly — a function returns one value. But you can return a struct, or use pointer parameters to write into caller variables.
Option 1 — return a struct (cleanest for small groups of values):
typedef struct { int min, max; } MinMax;
MinMax find_min_max(int *a, int n) {
MinMax r = {a[0], a[0]};
for (int i = 1; i < n; i++) {
if (a[i] < r.min) r.min = a[i];
if (a[i] > r.max) r.max = a[i];
}
return r;
}
Option 2 — use pointer parameters for output values:
void divmod(int a, int b, int *q, int *r) {
*q = a / b;
*r = a % b;
}
int quotient, remainder;
divmod(17, 5, "ient, &remainder); /* q = 3, r = 2 */
Option 3 — return a pointer to a static or heap array (rarely the best choice; watch the lifetime carefully). The struct option is usually the clearest when the return values belong together.
Recursion
Q8. Explain the concept of recursion. Provide an example of a recursive function.
Answer: Recursion is a function calling itself to solve smaller versions of the same problem — with a base case to stop.
The factorial example — factorial(5) = 5 × 4 × 3 × 2 × 1:
int factorial(int n) {
if (n <= 1) return 1; /* base case — stops the recursion */
return n * factorial(n - 1); /* recursive call */
}
How it runs for factorial(4):
factorial(4) = 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * 1))
= 24
Two rules every recursive function must follow:
- A base case — a condition that stops the recursion. Without it, the function calls itself until the stack overflows (a crash).
- Progress toward the base case — each call must make the problem smaller.
factorial(n-1)is smaller thanfactorial(n);factorial(n)calling itself would loop forever.
Recursion is elegant for trees, divide-and-conquer, and problems that naturally break into the same shape. For simple counted loops, an iterative version is usually faster and uses less memory.
Full tutorial: Recursion in C — with examples
Q9. What happens if a recursive function has no base case?
Answer: It calls itself until the stack runs out of space — then the program crashes with a stack overflow.
Each recursive call uses a stack frame: the function's local variables, parameters, and return address. Stack space is limited (typically 1–8 MB per thread). Once it's exhausted, the program gets a segmentation fault (or equivalent).
int infinite(int n) {
return infinite(n - 1); /* no base case — will crash */
}
Some compilers detect tail recursion and optimize it into a loop, but you can never rely on that. Always write an explicit base case, and test with the smallest input (n = 0 or n = 1) to make sure it stops.
Q10. When should you use recursion instead of a loop?
Answer: When the problem naturally breaks into smaller versions of itself — trees, divide-and-conquer, or backtracking.
Good cases for recursion:
- Tree and graph traversal — walking children of a node is naturally recursive.
- Divide-and-conquer — quicksort, mergesort, binary search.
- Backtracking — puzzles, path finding, permutations.
- Mathematical definitions — factorial, Fibonacci, Towers of Hanoi.
Stick to loops when the problem is a simple count or a linear scan — iterating an array, summing numbers, reading a file. Recursion adds function-call overhead and stack usage, which buys nothing for a flat loop.
Pointers, callbacks, and storage
Q11. What are function pointers in C, and how are they useful?
Answer: A function pointer stores the address of a function — you can call it through the pointer, pass it as an argument, or store it in a table.
Syntax:
int add(int a, int b) { return a + b; }
int (*fp)(int, int) = add; /* fp points to add */
int r = fp(3, 4); /* call through the pointer — r = 7 */
Why they matter:
- Callbacks: pass a comparison function to
qsort, or a handler to an event system. - Dispatch tables: an array of function pointers lets you map a value to a function without a long
switch— the classic "jump table" pattern. - Polymorphism in C: combine a struct with a function pointer and you get OOP-style virtual methods, as used in the Linux kernel and many C libraries.
The tricky part is the declaration syntax — int (*fp)(int, int) is not the same as int *fp(int, int). Use typedef to keep it readable:
typedef int (*bin_op)(int, int); bin_op fp = add; /* much easier to read */
Full tutorial: Pointer to a Function in C
Q12. Explain the concept of a callback function in C.
Answer: A callback is a function you pass to another function — the receiving function calls it at the right moment.
The receiving function doesn't know what the callback does; it just knows how to call it:
void for_each(int *a, int n, void (*cb)(int)) {
for (int i = 0; i < n; i++) cb(a[i]);
}
void print(int x) { printf("%d\n", x); }
void square(int x) { printf("%d\n", x * x); }
int main(void) {
int a[3] = {1, 2, 3};
for_each(a, 3, print); /* calls print on each element */
for_each(a, 3, square); /* calls square on each element */
return 0;
}
The standard library is full of callbacks — qsort takes a comparison callback, and signal handlers are callbacks from the OS. Event-driven programs, GUI frameworks, and plugin systems all rely on this pattern.
Q13. What is the purpose of the static keyword when used with a function?
Answer: It limits the function's visibility to the current source file — other files can't call it.
By default, every function has external linkage — any other source file can call it if it knows the prototype. Adding static makes the function internal to the file:
/* helper.c */
static int internal_helper(int x) { /* only visible in helper.c */
return x * 2;
}
int public_api(int x) { /* visible to everyone */
return internal_helper(x) + 1;
}
Why this is useful:
- No name clashes: two files can both have a
static int helper()with no conflict at link time. - Encapsulation: private functions stay private — a clear module boundary.
- Compiler optimization: the compiler knows the function can only be called from within the file, so it can inline it or optimize more aggressively.
static on a local variable inside a function means something different — the variable keeps its value between calls. Both uses are common; don't confuse them.
Full tutorial: Storage Classes in C — static, extern, auto, register
Q14. How do you create a function that accepts a variable number of arguments?
Answer: Use the ... ellipsis in the prototype and the va_list macros from <stdarg.h>.
#include <stdarg.h>
#include <stdio.h>
int sum(int count, ...) {
va_list args;
va_start(args, count); /* start after the last named param */
int total = 0;
for (int i = 0; i < count; i++) {
total += va_arg(args, int); /* read next int */
}
va_end(args);
return total;
}
int main(void) {
printf("%d\n", sum(3, 10, 20, 30)); /* 60 */
return 0;
}
Key rules:
- You must know or tell the function how many arguments to expect — usually via a count parameter or a sentinel value.
- There is no type checking on the variadic arguments. If you call
va_arg(args, int)but pass adouble, you get garbage. - Always pair
va_startwithva_end.
printf and scanf are the most common examples of this pattern. For anything with mixed types, prefer passing a struct or an array — variadic functions are easy to get wrong.
Q15. What is the purpose of the void keyword in function declarations?
Answer: void as a return type means the function returns nothing; void in the parameter list means it takes no arguments.
void print_hello(void) { /* no parameters, returns nothing */
printf("hello\n");
}
Two uses:
- Return type
void— the function doesn't send a value back. You can't use its "result" in an expression. - Parameter list
(void)— the function takes no arguments. This is not the same as an empty parameter list:()in C89 means "unspecified arguments," so(void)is the correct way to say "takes nothing."
In modern C, int func() means "no prototype — accepts anything" and int func(void) means "takes zero arguments." Always use (void) when a function takes no parameters — it lets the compiler catch mistakes at the call site.
Q16. Describe the use of the inline keyword with functions in C.
Answer: inline is a hint that the compiler should insert the function body at the call site instead of making a real function call.
static inline int square(int x) {
return x * x;
}
What it actually does:
- Removes call overhead: no function call means no parameter passing, no return jump. For tiny functions called in hot loops, this can matter.
- Enables further optimization: the compiler can fold the body into surrounding code — for example,
square(5)may become the constant25.
Two warnings:
inlineis only a hint. The compiler can ignore it. GCC and Clang will happily inline smallstaticfunctions even without the keyword.- Aggressive inlining grows the binary — a large function inlined at 50 call sites becomes 50 copies of the code. Use
inlineon small, hot functions, not everywhere.
In C99 and later, inline interacts with linkage in ways that matter for header files. Use static inline for simple header helpers — that's the safe, common pattern.
Q17. What is function overloading? Does C support it?
Answer: Overloading means two functions with the same name but different parameter lists. C does not support it.
In C++, you can write:
/* C++ only — NOT valid C */ int add(int a, int b); double add(double a, double b);
In C, function names are just symbols — add is add, and there is no concept of overload resolution. Two definitions of add in the same translation unit are a compile error ("redefinition"), and in different translation units they cause a link error ("multiple definition").
How C programmers achieve the same effect:
- Different names:
add_int,add_double. - Generic macros:
#define add(a, b) _Generic((a), int: add_int, double: add_double)(a, b)(C11_Generic). - void pointers: one function that handles multiple types via
void *— flexible but unsafe.
Errors and edge cases
Q18. Can a function in C return a pointer to a local variable? Why or why not?
Answer: You can write it, but it's a bug — the local variable is destroyed when the function returns, so the pointer points to freed memory.
int *bad(void) {
int x = 42;
return &x; /* WRONG — x is gone after return */
}
The local variable lives on the stack. When the function returns, that stack space is reclaimed and may be overwritten by the next function call. Reading through the returned pointer is undefined behaviour — it may return the old value, or garbage, or crash.
Safe alternatives:
- Return a static variable — survives the return, but only one copy exists. Not thread-safe.
- Return a heap pointer —
mallocthe value; the caller mustfreeit. - Write into a caller-supplied buffer — usually the cleanest API design.
Q19. How do you handle errors or exceptions in C functions?
Answer: C has no exceptions. You check return values, use sentinel values like -1 or NULL, set errno, or use setjmp/longjmp for non-local jumps.
The standard patterns:
- Return a status code — the function returns
0for success and a negative value for each error type. This is the most common pattern in C libraries. - Set
errno— system calls and many library functions seterrnoon failure. Check it right after the call and translate it withperrororstrerror. - Return
NULLor a sentinel —mallocreturnsNULLon failure; some functions return-1. - Out-parameter for the error — pass a pointer where the function writes the error code, keeping the return value for the real result.
FILE *f = fopen("data.txt", "r");
if (f == NULL) {
perror("fopen"); /* prints the system's error message */
return -1;
}
The golden rule: always check return values. Almost every classic C bug — crashes, corrupted data, silent failures — traces back to a return value that was ignored.
Q20. How do you declare a function that takes no arguments in C?
Answer: Use (void) — as in int func(void);. An empty parameter list () means "unspecified arguments" in C, not "no arguments."
int get_value(void); /* correct — takes no arguments */ int get_value(); /* wrong in C — takes unknown arguments */
The difference matters:
int func(void);— the compiler will error if you try to callfunc(5). This is what you want.int func();— in C89 the compiler allows any number of arguments. C99 kept this behaviour for backwards compatibility, but modern compilers warn with-Wstrict-prototypes.
Rule for new code: always write (void) when a function takes no parameters. It documents intent and lets the compiler catch mistakes.
Frequently Asked Questions
What is the difference between a function and a macro in C?
A function is checked by the compiler — argument types, return types, side effects all matter. A macro is text substitution done by the preprocessor before the compiler even sees the code. Macros are faster (no call overhead) but dangerous (no type checking, tricky evaluation order). Use functions by default; use macros only for constant-like values or when you need the substitution behaviour. static inline gives you the speed of a macro with the safety of a function — always prefer it over a macro for real logic.
Can a C function take another function as an argument?
Yes — via a function pointer. The parameter is declared as a pointer to a function with a specific signature. void for_each(int *a, int n, void (*cb)(int)) takes a callback. This is how qsort works and how most event systems in C are built.
What is the maximum number of parameters a C function can have?
The C standard requires at least 127 parameters for a function definition, but practical limits vary by compiler. In real code, if you're approaching 5+ parameters, it's usually a sign the function is doing too much or should take a struct. Parameters also cost stack space and register pressure — fewer is better.
What is the main() function in C and why is it special?
main is the entry point — the OS or the C runtime calls it first. Its return value becomes the process exit status (0 = success, non-zero = error). It has two standard forms: int main(void) and int main(int argc, char *argv[]). Every other function must be called from something; main is called automatically by the runtime.
Why is it bad practice to return a pointer to a local variable?
Because the local variable is destroyed when the function returns — the pointer then points to memory that no longer belongs to you. The compiler may warn about it (-Wreturn-local-addr in GCC), but if it doesn't, the bug is silent: the pointer may work in testing and fail in production. Use a static variable, a heap pointer, or a caller-supplied buffer instead.
💡 Tip: Function questions in interviews come down to four things: knowing what a prototype does and why it matters, understanding the call by value vs call by reference distinction, being able to write a recursive function with a base case, and being able to declare and use a function pointer. If you can explain those four fluently with small examples, you're set for any function question.