What Is a Function?
A function is a self-contained section of code that performs a specific task. Functions are the primary tool for breaking large programs into manageable pieces (top-down design).
Advantages of using functions:
- Cleaner design — hide implementation details; overall logic is easier to follow.
- Reusability — write once, call anywhere.
- Team development — each function can be developed as an independent unit.
- Easier debugging — functions can be tested individually.
Function Declaration, Definition, and Variables
Function Declaration (Prototype)
Tells the compiler the function name, return type, and parameter types before use.
return_type function_name(parameter_type_list);
// Examples:
int ccmit(int bsit, int bscs);
void ccmit();
float ccmit(float x, float y);
Function Definition
return_type function_name(parameter list) {
local variable declarations;
statements;
return value;
}
// Example:
double twice(double x) {
return 2.0 * x;
}
If return type is void, the function returns no value.
Local vs. Global Variables
Local variables:
- Declared inside a function body.
- Accessible only within that function.
- Created on call, destroyed on return.
- Must be explicitly initialized (no automatic zero).
Global variables:
- Declared outside all functions.
- Accessible from any function.
- Initialized to zero if unspecified.
- Persist for the program's lifetime. Use sparingly — they make functions less self-contained.
Call by Value vs. Call by Reference
Call by Value
Arguments are passed as copies — changes inside the function do not affect the original.
void funct_sample(int y) {
y *= 3;
printf("New value of y: %d", y); // prints 15
}
main() {
int n = 5;
printf("n before call: %d", n); // 5
funct_sample(n);
printf("n after call: %d", n); // still 5 — unchanged
}
Call by Reference (Pointers)
To allow a function to modify a variable in the caller, pass the address using &. Inside the function, use * to access the value at that address.
&variable— "the address of variable"*pointer— "the value at the address held by pointer"
void compute_rating(float midterm, float final, float *rating) {
*rating = (midterm + final) / 2;
}
main() {
float mid, fin, fin_grd;
scanf("%f", &mid);
scanf("%f", &fin);
compute_rating(mid, fin, &fin_grd);
printf("Final rating = %f", fin_grd);
}
&fin_grd passes the address. *rating = ... stores a value directly into that memory location, so the change is visible in main() after the call.
Practice Exercises — Lesson 6
Try It: Functions
Try calling add() with different numbers, or write a new function that multiplies two values.