User-defined Functions
Open in the Padhaiko app7.1 Introduction to function
A function is a self-contained, named block of code designed to perform a specific, well-defined subtask. Every C program begins execution at main() and may call other functions, which fall into two groups:
- Library (Built-in) Functions: Precompiled standard functions declared in headers such as
<stdio.h>(printf(),scanf()) and<math.h>(sqrt(),pow()). - User-Defined Functions: Functions written by the programmer to decompose complex logic into modular, reusable units.
7.2 Advantages of function
Decomposing a program into user-defined functions provides major engineering benefits:
- Modularity (Divide and Conquer): Breaks large problems into smaller, independent subproblems that are easier to design, understand, and reason about.
- Code Reusability: Write a logic block once and invoke it from multiple places with different arguments, eliminating duplication.
- Easier Debugging and Testing: Individual functions can be unit-tested and fixed in isolation without breaking unrelated code.
- Team Collaboration and Maintainability: Different programmers can implement separate functions concurrently using agreed prototypes.
- Reduced Program Size and Clear Abstraction: Callers only need to know what a function does (its signature), not how it works internally.
7.3 Elements of user-defined function
A user-defined function involves three distinct elements: function prototype (declaration), function call, and function definition.
7.3.1 Function definition
The function definition provides the actual body (implementation) of the function:
return_type function_name(parameter_list) {
/* local declarations and statements */
return expression; /* omitted or 'return;' if return_type is void */
}- Function Header:
return_type function_name(parameter_list)specifies the returned data type (defaulting tovoidif nothing is returned), the function identifier, and the formal parameter list. - Function Body: The compound block
{ ... }containing local variables, logic, and optionalreturnstatement.
7.3.2 Function prototype
A function prototype (declaration) informs the compiler of a function's name, return type, and parameter types before it is called (typically placed above main() or in a .h header file). Parameter names are optional in prototypes, and the prototype ends with a semicolon ;:
int add(int a, int b); or int add(int, int);
Prototypes enable compile-time type checking of arguments and implicit argument conversion when a caller passes compatible types (e.g., int to double).
7.3.3 Function parameters
| Aspect | Actual Parameters (Arguments) | Formal Parameters |
|---|---|---|
| Where They Appear | Inside the function call, e.g., sum(x, y + 2) | Inside the function header definition, e.g., int sum(int a, int b) |
| What They Can Be | Variables, constants, or expressions | Must be typed variable declarations |
| Memory & Lifetime | Evaluated before the call and copied into the formal parameters | Local variables created on the call stack when the function starts, destroyed on return |
7.4 Storage class
A storage class specifier in C defines four attributes of a variable or function: storage location (RAM vs. CPU register), default initial value, scope (visibility), and lifetime (duration in memory).
| Storage Class | Storage Location | Default Initial Value | Scope | Lifetime |
|---|---|---|---|---|
auto (default for locals) | Stack (RAM) | Garbage (indeterminate) | Local to enclosing block | Until enclosing block finishes |
register | CPU register (if available, else stack) | Garbage (indeterminate) | Local to enclosing block | Until enclosing block finishes (cannot apply & address-of) |
static (local) | Data / BSS segment (RAM) | 0 | Local to enclosing block | Entire program execution (retains value across calls) |
static (global) | Data / BSS segment (RAM) | 0 | Internal linkage (current .c file only) | Entire program execution |
extern | Data / BSS segment (RAM) | 0 | External linkage (shared across .c files) | Entire program execution |
7.5 Scope rules
Scope defines the region of program text where an identifier can be legally accessed:
- Block (Local) Scope: Variables declared inside
{ ... }(or function parameters) are visible only from their declaration to the closing}of that block. An inner block variable with the same name shadows (temporarily hides) an outer variable. - File (Global) Scope: Variables declared outside all functions are visible from their declaration point to the end of the source file (and across files unless marked
static). - Function Prototype Scope: Parameter names inside a prototype (
int f(int x);) are local to that prototype line only.
7.6 Category of functions
Based on whether a function accepts arguments and returns a value, user-defined functions fall into four standard categories:
7.6.1 Functions with no arguments and no return values
The caller passes no data and expects no result back (void greet(void);). The function handles its own input, processing, and output internally.
7.6.2 Functions with arguments and no return values
The caller passes input data into the function, which processes and displays or mutates data without returning a value (void print_line(int len, char ch);).
7.6.3 Functions with arguments and return values
The most versatile and reusable category: the caller supplies inputs, the function computes a result and sends it back via return (double power(double base, int exp);).
7.6.4 Functions with no arguments and return values
The function takes no parameters from the caller (for example, prompting the user for input or reading a sensor) and returns the obtained value (int read_positive(void);).
| Category | Prototype Example | Sample Call | Primary Use |
|---|---|---|---|
| No args, no return | void banner(void); | banner(); | Fixed UI banners, greetings |
| Args, no return | void show_sum(int a, int b); | show_sum(3, 5); | Formatted printing of given inputs |
| Args and return | int max2(int a, int b); | m = max2(3, 5); | Reusable pure computations |
| No args, return | int get_choice(void); | c = get_choice(); | Validated input readers, random/status getters |
7.7 Recursive functions
Recursion and Its Two Mandatory Parts
A recursive function is a function that calls itself directly or indirectly to solve a smaller instance of the same problem. Every terminating recursion requires:
- Base Case: One or more simplest conditions answered directly without making another recursive call (prevents infinite recursion and stack overflow).
- Recursive Case: Reduces the problem toward the base case and calls the function on the smaller subproblem.
Each active recursive call pushes a new stack frame (holding its own parameters, local variables, and return address) onto the call stack. Once the base case returns, stack frames unwind in Last-In First-Out (LIFO) order.
| Aspect | Recursion | Iteration (Loops) |
|---|---|---|
| Repetition Mechanism | Repeated function self-calls | for, while, or do-while loop |
| Termination | Stops when a base case is reached | Stops when loop condition becomes false |
| Memory & Speed | Higher stack memory (O(depth) frames) and call overhead | Constant O(1) loop control overhead; faster in C |
| Readability | Natural and concise for trees, factorial, Fibonacci, Tower of Hanoi | Best for linear counting and array scans |
7.8 Function call by values and reference
C natively passes every argument by value. Passing by reference is simulated in C by passing the memory address (pointer) of a variable.
| Aspect | Call by Value | Call by Reference (via Pointers) |
|---|---|---|
| What Is Passed | A copy of the variable's value | The memory address (&var) of the variable |
| Effect on Caller Variable | Modifying formal parameter does not alter the original caller variable | Dereferencing *ptr directly modifies the caller's original variable |
| Multiple Outputs | Limited to a single return value | Can update multiple caller variables simultaneously (e.g., swap(&x, &y)) |
7.9 Passing array and string to function
When an array (or string char[]) is passed to a function, C does not copy all elements onto the stack. Instead, the array name decays into a pointer to its first element (&arr[0]).
- 1D Array / String Parameter Syntax:
int sum_array(int arr[], int n);is identical toint sum_array(int *arr, int n);. Because the array decays to a pointer,sizeof(arr)inside the function returns the pointer size (4 or 8 bytes), not the array's byte length—so always pass the element countnas a separate parameter (for strings,'\0'marks the end). - Mutability: Changes made to
arr[i]inside the function modify the caller's original array directly. Prefix withconst(const int arr[]) when the function should only read the array.
Worked Examples
1
Write a recursive C function long fact(int n) to compute the factorial of a non-negative integer n, and trace the call stack and unwinding steps for fact(4).
Recursive Definition of fact(n):
- Base case:
0! = 1and1! = 1(if (n <= 1) return 1;). - Recursive case:
n! = n * (n - 1)!(return n * fact(n - 1);).
#include <stdio.h>
long fact(int n) {
if (n <= 1) {
return 1;
}
return n * fact(n - 1);
}
int main(void) {
printf("4! = %ld\n", fact(4));
return 0;
}fact(4) returns 24 (and fact(5) returns 120).
2
Trace the output of the following C program demonstrating static local variables, global/local scope shadowing, and call by value vs. call by reference:
#include <stdio.h>
int g = 10;
int counter(void) {
static int c = 0;
c++;
return c;
}
void modify(int a, int *b) {
int g = 99;
a += g;
*b += 5;
}
int main(void) {
int x = 1, y = 2;
modify(x, &y);
printf("x=%d y=%d g=%d\n", x, y, g);
int c1 = counter();
int c2 = counter();
int c3 = counter();
printf("c=%d %d %d\n", c1, c2, c3);
return 0;
}Tracing modify(x, &y):
- Inside
modify,int g = 99;is a local variable that shadows globalg = 10without altering globalg. areceives a copy ofx(1) by value;a += 99makes locala = 100, leaving caller'sx = 1unchanged.breceives&y(address ofy);*b += 5updatesydirectly from2to7.- When
modifyreturns, globalgis still10. So line 1 printsx=1 y=7 g=10.
Tracing Three Calls to counter(): static int c = 0; is initialized only once and persists across calls:
- First call:
cbecomes1, returns1. - Second call:
cretains1, increments to2, returns2. - Third call:
cretains2, increments to3, returns3.
Output:
x=1 y=7 g=10
c=1 2 33
Write a user-defined C function int find_max(const int a[], int n) that takes an integer array and its size, returns the maximum element without modifying the array, and demonstrate calling it from main() on {4, 9, 2, 11, 4}.
Designing find_max(): Initialize int mx = a[0]; and scan indices 1 to n - 1. Using const int a[] ensures the compiler prevents accidental modification of the caller's array.
#include <stdio.h>
int find_max(const int a[], int n);
int main(void) {
int data[] = {4, 9, 2, 11, 4};
int n = 5;
printf("Max = %d\n", find_max(data, n));
return 0;
}
int find_max(const int a[], int n) {
int mx = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > mx) {
mx = a[i];
}
}
return mx;
}find_max(data, 5) prints Max = 11.
Exercises
Exercises — User-defined Functions
Differentiate between a function prototype, function definition, and function call. Distinguish formal parameters from actual parameters with an example.
Three Function Elements:
- Function Prototype: Declaration ending with
;telling the compiler the return type, name, and parameter types before use (e.g.,int square(int);). - Function Definition: Full implementation with body
{ ... }(e.g.,int square(int n) { return n * n; }). - Function Call: Statement/expression invoking execution (e.g.,
int r = square(5);).
Actual vs. Formal Parameters: In square(5), 5 is the actual parameter (argument) passed by the caller, while n in int square(int n) is the formal parameter receiving the copy inside the function.
A prototype declares the signature, a definition provides the body, and a call executes the function. Actual parameters are caller expressions passed in the call, whereas formal parameters are local variables in the function header receiving those values.
Compare the four storage classes in C (auto, register, static, extern) with respect to storage location, default initial value, scope, and lifetime.
Storage Class Summary:
auto: Stack memory; garbage initial value; block scope; lifetime ends when block exits.register: Requests CPU register storage; garbage initial value; block scope; block lifetime;&cannot be applied.static: Static data segment; default initial value0; block scope (if local) or file scope (if global); lifetime spans entire program execution.extern: Static data segment; default initial value0; global/cross-file linkage; lifetime spans entire program execution.
auto and register have garbage defaults and block lifetime (stack vs. CPU register request), whereas static and extern initialize to 0 and persist for the entire program run (static restricts visibility to block/file; extern shares across files).
Explain call by value vs. call by reference in C. Write a void swap(int *a, int *b) function using pointers and show why void swap(int a, int b) fails to swap variables in main().
Why Call by Value Fails to Swap Caller Variables: In void swap(int a, int b), a and b are independent local copies on the stack. Swapping a and b inside swap leaves the caller's original variables untouched.
Working Pointer-Based swap:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
/* Caller invokes: swap(&x, &y); */Here *a and *b dereference the caller's addresses directly, exchanging x and y in memory.
Call by value passes copies so caller variables remain unchanged; call by reference passes addresses (&x, &y) into pointer parameters (int *a, int *b) so *a and *b swap the original memory contents.
What are the two essential components of a recursive function? Write a recursive function int fib(int n) (with fib(0) = 0, fib(1) = 1) and find the value of fib(6).
Two Essential Components:
- Base Case: Terminating condition(s) solved directly (
if (n <= 1) return n;). - Recursive Case: Self-call on strictly smaller subproblems (
return fib(n - 1) + fib(n - 2);).
Evaluating fib(6):
fib(0) = 0,fib(1) = 1fib(2) = 1 + 0 = 1fib(3) = 1 + 1 = 2fib(4) = 2 + 1 = 3fib(5) = 3 + 2 = 5fib(6) = 5 + 3 = 8
A recursive function requires a base case and a recursive step moving toward it. For fib(0)=0, fib(1)=1, fib(6) evaluates to 8.
When an array is passed to a C function, why is it passed by address rather than copied by value? Write a C function int count_vowels(const char str[]) and evaluate its return value on "Computer Programming".
Why Arrays Decay to Pointers: Copying a large array on every function call would waste stack space and CPU time. Instead, C passes only the starting address (&str[0]) as a pointer, allowing O(1) call overhead while letting the function read (or modify, unless const) the caller's array directly.
Function and Trace on "Computer Programming":
int count_vowels(const char str[]) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = str[i];
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U') {
count++;
}
}
return count;
}Vowels in "Computer Programming": 'o', 'u', 'e' in "Computer" (3) and 'o', 'a', 'i' in "Programming" (3), totaling 6 vowels.
Arrays decay to a pointer to their first element to avoid expensive stack copies. count_vowels("Computer Programming") counts o, u, e, o, a, i and returns 6.