Functions
Functions in C: prototypes, definitions, calling, parameters and arguments, return values, scope and linkage, pass-by-value vs pointers, arrays as parameters, recursion reference, function pointers (intro), and best practices.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Functions let you break a large C program into small, reusable, and testable parts. Engineers use functions to separate hardware drivers, algorithms, and user interfaces, to reuse logic across projects, to test each part in isolation, and to improve readability and maintenance.
Key ideas
- Function definition: The full body of a function, which specifies the return type, function name, parameter list with types, and the statements to execute, enclosed in braces
{}. Exact statement: “A function definition provides storage and code for the function and must be defined exactly once with external linkage across the entire program; functions declaredstatichave internal linkage and may have separate definitions in different translation units.” - Function declaration (prototype): A declaration that specifies the function’s name, return type, and the number, order, and types of its parameters, without the body, and ends with a semicolon. Exact statement: “A function prototype causes the compiler to check function calls for correct number and types of arguments and to perform necessary implicit conversions.” Since C99, a declaration (prototype or earlier definition) must be visible before any call; calls to undeclared functions are not allowed.
- Return type: The type of value a function gives back using
return. If no value is returned, the type must bevoid. Exact statement: “Every non-voidfunction must return a value of its declared return type along all execution paths; if control reaches the end of the function without areturn, the behavior is undefined.” - Parameters vs. arguments: Parameters are the variables in the function definition that receive data; arguments are the expressions supplied in the function call. Exact statement: “At call time, argument values are converted to the parameter types as specified by the function prototype.”
- Pass-by-value (C rule): In C, function arguments are always passed by value (a copy of each argument expression is made). To allow a function to modify a caller’s variable, pass the address (pointer) of that variable. This is often called “simulating pass-by-reference.”
- Scope and lifetime with functions: Parameters and variables declared inside a function have block scope and automatic storage duration by default; they exist only while the function runs. Identifiers at file scope that name functions have file scope and external linkage by default, unless declared
static(then internal linkage). Reference: deeper study in the topic “Storage classes.” - Function
main: The program entry point in a hosted C environment. Exact forms recommended:int main(void)orint main(int argc, char *argv[]). It must return anintto the operating system;return 0;signals success. If control reaches the end ofmainwithout areturn, it is equivalent to returning0(since C99). - Void and no parameters:
voidas a return type means “no value returned.” In a parameter list,voidmeans “no parameters.” Example:int f(void)means f takes no parameters;int f()(old-style) means an unspecified parameter list and should be avoided in modern C. - Function overloading: C does not support function overloading (same name with different parameter types or counts). Each function name must be unique at link time within its linkage.
- Inline, static, extern (function linkage and visibility):
staticat file scope gives a function internal linkage (visible only in that translation unit).externdeclares a function with external linkage (default).inlinesuggests the compiler to substitute the function body at call site; behavior depends on the compiler and optimization; correctness must not rely on inlining. When placing inline functions in headers, preferstatic inlineto avoid multiple-definition/linkage issues. - Arrays as parameters: When you pass an array to a function, it decays to a pointer to its first element. Therefore, the parameter type
int a[]is the same asint *a. The function also usually needs the array length as a separate parameter. - Const correctness: Use
constin parameters likeconst int *ato promise not to modify the array elements; this improves safety and allows more compiler optimizations. - Multiple results: A C function returns a single value. To return more than one result, use pointer parameters, return a
struct, or write outputs into caller-provided arrays/buffers. - Recursion (overview): A function calling itself to solve a smaller subproblem. Needs a base case and a step that reduces the problem size. Full treatment is in the topic “Recursion.”
- Function pointer (intro): A variable that stores the address of a function with a given signature and can be used to call it. Used for callbacks (e.g.,
qsort). Syntax is tricky; see “Formulas — syntax.”
Diagram to draw for stack behavior in exams (describe):
- Draw a vertical stack labeled “Call Stack” with frames (boxes) for
main, thencaller, thencalleeon top. In each frame, label: return address, saved registers (conceptual), parameters, local variables. Use arrows from caller variables to copies in callee parameters to show pass-by-value. For pointer parameters, draw an arrow from the callee’s parameter to the same memory location as the caller’s variable, showing shared access via the address.
Formulas
return_type function_name(parameter_type1 name1, parameter_type2 name2, ...);
Example: int max(int a, int b);
- Function definition:
return_type function_name(parameter_declarations) { statements }Example:int max(int a, int b) { return (a > b) ? a : b; } - Function call:
result = function_name(arg1, arg2, ...); - Returning a value:
return expression;(type of expression must be compatible with return_type) or forvoidfunction:return; - No-parameter function (modern C):
int f(void);// declaration and definition use(void) - Array parameter (decays to pointer):
void read_arr(int a[], int n);is same asvoid read_arr(int *a, int n); - Pointer parameter to allow modification of caller data:
void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; } - Const parameter examples:
int sum(const int *a, int n); - Static function (internal linkage):
static int helper(int x) { ... } - Inline hint (if supported by compiler):
inline int sqr(int x) { return x * x; } - Function pointer declaration and call:
int (*fp)(int, int) = &max; int r = fp(3, 4); - Main function signatures:
int main(void)int main(int argc, char *argv[])
Worked examples
Example 1: Compute GCD of two positive integers using a function (Euclidean algorithm) Complete C program:
#include <stdio.h>
// Prototype
int gcd(int a, int b);
int main(void) {
int x, y;
printf("Enter two positive integers: ");
if (scanf("%d %d", &x, &y) != 2) {
printf("Invalid input\n");
return 1;
}
if (x <= 0 || y <= 0) {
printf("Inputs must be positive integers\n");
return 1;
}
int g = gcd(x, y);
printf("GCD(%d, %d) = %d\n", x, y, g);
return 0;
}
// Definition: iterative Euclidean algorithm
int gcd(int a, int b) {
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a; // a is the gcd
}
Sample input:
18 24
Exact output:
Enter two positive integers: GCD(18, 24) = 6
Example 2: Show pass-by-value and modification via pointers (swap) Complete C program:
#include <stdio.h>
// Prototypes
void swap_by_value(int a, int b);
void swap_by_pointer(int *a, int *b);
int main(void) {
int x, y;
printf("Enter two integers: ");
if (scanf("%d %d", &x, &y) != 2) {
printf("Invalid input\n");
return 1;
}
printf("Before swap_by_value: x = %d, y = %d\n", x, y);
swap_by_value(x, y);
printf("After swap_by_value: x = %d, y = %d\n", x, y);
printf("Before swap_by_pointer: x = %d, y = %d\n", x, y);
swap_by_pointer(&x, &y);
printf("After swap_by_pointer: x = %d, y = %d\n", x, y);
return 0;
}
void swap_by_value(int a, int b) {
int t = a; a = b; b = t; // only swaps local copies
}
void swap_by_pointer(int *a, int *b) {
int t = *a; *a = *b; *b = t; // swaps caller's variables via addresses
}
Sample input:
5 9
Exact output:
Enter two integers: Before swap_by_value: x = 5, y = 9
After swap_by_value: x = 5, y = 9
Before swap_by_pointer: x = 5, y = 9
After swap_by_pointer: x = 9, y = 5
Example 3: Sum and average of an array using functions (arrays as parameters, const correctness) Complete C program:
#include <stdio.h>
// Prototypes
int sum_array(const int *a, int n);
double average_array(const int *a, int n);
int main(void) {
int n;
printf("Enter number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0) {
printf("Invalid n\n");
return 1;
}
int arr[100];
if (n > 100) {
printf("n too large (max 100)\n");
return 1;
}
printf("Enter %d integers: ", n);
for (int i = 0; i < n; i++) {
if (scanf("%d", &arr[i]) != 1) {
printf("Invalid input\n");
return 1;
}
}
int s = sum_array(arr, n);
double avg = average_array(arr, n);
printf("Sum = %d\n", s);
printf("Average = %.2f\n", avg);
return 0;
}
int sum_array(const int *a, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += a[i];
return s;
}
double average_array(const int *a, int n) {
if (n == 0) return 0.0; // guard
return (double)sum_array(a, n) / (double)n;
}
Sample input:
5
10 20 30 40 50
Exact output:
Enter number of elements: Enter 5 integers: Sum = 150
Average = 30.00
Common mistakes
- Assuming C has pass-by-reference automatically; writing
void swap(int a, int b)and expecting caller variables to swap. In C, you must pass addresses (int *). - Using
int f()(old-style, unspecified parameter list) instead ofint f(void)for a no-parameter function, causing accidental arguments to be accepted. - Returning the address of a local (automatic) variable, which becomes invalid after the function returns. Use
staticstorage, dynamic memory, or caller-provided buffers instead. - Missing
returnstatement in a non-voidfunction, or returning a value of the wrong type. - Not passing array length along with the array, causing out-of-bounds access.
- Name collisions across files when using the same helper function name without
staticfor internal linkage; leads to unexpected link-time conflicts. - Misdeclaring function pointers; forgetting parentheses in
int (*fp)(int)and accidentally declaringint *fp(int)(a function returning pointer to int) instead. - Printing prompts differently from sample outputs in exams; outputs must match exactly where required.
For your exam
- Short notes: arrays as parameters and decay,
constcorrectness,staticfunctions (internal linkage),inlinehint,mainsignatures. Include one or two lines of syntax. - Programs: small programs using functions — GCD, factorial or Fibonacci (often with recursion, covered under “Recursion”), menu-driven calculator with functions, array sum/average, swap via pointers. Include prototypes, proper return types, and clean I/O. Ensure the code compiles and the sample I/O is exact.
- Tracing questions: Given a program with function calls, predict the output. Show step-by-step parameter values and return values. If a stack-frame diagram is asked, draw as described under Key ideas.
- Concept checks: Identify errors in a piece of code involving prototypes, missing returns, or pass-by-value misunderstandings; correct them with reasons.
- Function pointer/callback basics: Write the declaration of a pointer to a function with a given signature, and show a simple call. Keep it minimal and accurate.
A full-marks answer typically includes: correct definitions in the first line, clean and correct syntax, a labeled diagram if asked, clearly separated functions with prototypes, and exact, tested output for programs.
Quick check
- State whether C uses pass-by-value or pass-by-reference for function arguments. How can a function modify a caller’s variable?
- What is the difference between
int f()andint f(void)in modern C? - When you pass
int a[10]to a function, what parameter type does it become, and what extra information should you pass?
Answers: 1) C uses pass-by-value. To modify caller variables, pass their addresses (pointers) and dereference inside the function. 2) int f() declares a function with an unspecified parameter list (old-style) and should be avoided; int f(void) declares a function that takes no parameters. 3) It decays to int * (pointer to int); also pass the array length (e.g., int n = 10).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?