Defining Functions
Defining Functions in C
Functions break programs into manageable, reusable pieces.
Function declaration (prototype) Tells the compiler about a function before its definition. Placed at the top of the file or in a header:
int add(int a, int b); // declarationFunction definition The actual implementation:
int add(int a, int b) { return a + b; }Return values
return expression;exits the function and returns the value.voidfunctions usereturn;with no value (or omit it).
Parameters by value C passes all arguments by value — the function receives copies. Modifying a parameter does not affect the caller's variable.
void functions Perform side effects (printing, modifying via pointers) rather than computing a value.
Key points:
- Prototypes allow calling a function before its definition in the file.
void func(void)explicitly declares no parameters in C;void func()accepts any arguments in C89.- Function names and parameter names must follow identifier rules (letters, digits, underscore; not starting with a digit).
Code Examples
#include <stdio.h>
// Prototypes
int factorial(int n);
double power(double base, int exp);
int main(void) {
printf("5! = %d\n", factorial(5));
printf("2^10 = %.0f\n", power(2.0, 10));
return 0;
}
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
double power(double base, int exp) {
double result = 1.0;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}Prototypes let main() call factorial() and power() before their definitions. The compiler knows signatures from prototypes.
#include <stdio.h>
void printLine(char ch, int count) {
for (int i = 0; i < count; i++) {
putchar(ch);
}
putchar('\n');
}
void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
// Does NOT affect the caller
}
int main(void) {
printLine('=', 20);
printLine('-', 10);
int x = 5, y = 10;
swap(x, y);
printf("After swap: x=%d y=%d\n", x, y); // unchanged!
return 0;
}C passes by value — swap() gets copies of x and y. To swap the originals, you would pass pointers (covered in the next section).
Quick Quiz
1. What is a function prototype in C?
2. If you modify a parameter inside a C function, what happens to the caller's variable?
Was this lesson helpful?