Functions in C
A function is a self-contained block of code that performs a specific task. Writing functions makes code modular, reusable, and much easier to debug.
1. Declaring Function Prototypes
C compiles code sequentially from top to bottom. If a function is called in main() before it is defined, compilation will fail unless you provide a function prototype (declaration) at the top of the file:
int getSquare(int num); // Function prototype: tells compiler signature
2. Anatomy of a Function
A function definition consists of a return type, a descriptive name, parameter declarations, and the function body:
#include <stdio.h>
// 1. Prototype
double calculateArea(double width, double height);
int main() {
// 2. Function Call
double area = calculateArea(5.5, 4.0);
printf("Area: %.2lf\n", area);
return 0;
}
// 3. Function Definition
double calculateArea(double width, double height) {
return width * height; // returns double value to caller
}
3. Pass-by-Value (Parameter Copying)
By default, variables passed to functions are passed by value. This means C copies the value of the variable into a new parameter variable inside the function. Modifying the parameter inside the function does not affect the original variable in the calling function:
#include <stdio.h>
void incrementValue(int x) {
x = x + 1;
printf("Inside function: x = %d\n", x);
}
int main() {
int num = 10;
incrementValue(num); // Passes copy of num
printf("Inside main: num = %d\n", num); // num is still 10!
return 0;
}
If you want a function to modify a variable directly, you must pass its address using pointers (Pass-by-Reference).