Functions in C
Modular code blocks, parameter passing mechanisms, and recursion
What is a Function?
A function is a self-contained block of code designed to perform a specific task. C does not execute functions automatically; they must be invoked or called from within the program.
A function prototype informs the compiler about the function name, return type, and expected parameter list prior to its definition or invocation.
Types of Functions
1. Built-in (Library) Functions
Provided by standard C libraries and header files. Examples include: scanf(), printf(), strcpy(), strcmp(), strlen(), strcat().
2. User Defined Functions
Created by the programmer to meet specific program requirements. They can take parameters and optionally return values.
#include <stdio.h>
void add(int x, int y) {
int result = x + y;
printf("Sum of %d and %d is %d.\n", x, y, result);
}
void main() {
add(10, 15);
add(55, 64);
add(168, 325);
}Sum of 10 and 15 is 25. Sum of 55 and 64 is 119. Sum of 168 and 325 is 493.
Passing Parameters to a Function
There are two primary mechanisms for passing arguments into functions in C:
• Pass by Value: Copies the actual values into the function parameters. Changes made inside the function do not affect the caller’s original variables.
• Pass by Reference: Passes the memory addresses of variables using pointers. Changes made inside the function directly modify the original values in the caller.
Example: Pass by Value
#include <stdio.h>
void swap(int p1, int p2) {
int t = p2;
p2 = p1;
p1 = t;
printf("Inside swap: p1 = %d, p2 = %d\n", p1, p2);
}
int main() {
int a = 10, b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b);
swap(a, b);
printf("After: Value of a = %d and value of b = %d\n", a, b);
return 0;
}Before: Value of a = 10 and value of b = 20 Inside swap: p1 = 20, p2 = 10 After: Value of a = 10 and value of b = 20
Note
Example: Pass by Reference
#include <stdio.h>
void swap(int *p1, int *p2) {
int t = *p2;
*p2 = *p1;
*p1 = t;
printf("Inside swap: *p1 = %d, *p2 = %d\n", *p1, *p2);
}
int main() {
int a = 10, b = 20;
printf("Before: Value of a = %d and value of b = %d\n", a, b);
swap(&a, &b);
printf("After: Value of a = %d and value of b = %d\n", a, b);
return 0;
}Before: Value of a = 10 and value of b = 20 Inside swap: *p1 = 20, *p2 = 10 After: Value of a = 20 and value of b = 10
Note
Advantages of Functions
- Reduces program size and eliminates duplicate code.
- Facilitates modular design and structured programming.
- Makes debugging, testing, and maintenance significantly easier.
- Enhances code readability and logical separation of concerns.