C - Functions
Overview
Functions encapsulate reusable logic. A function has a return type, a name, parameters, and a body.
Learning Objectives
- Write function prototypes and definitions.
- Pass parameters by value and by address (via pointers).
- Return values and handle void functions.
Prerequisites
Basic Example
#include <stdio.h>
int add(int a, int b) { return a + b; }
void greet(const char *name) { printf("Hello, %s!\n", name); }
int main(void) {
printf("%d\n", add(2, 3));
greet("World");
}
Function Prototypes
// Declare before use (typically in headers)
int add(int, int);
void greet(const char*);
// Define later
int add(int a, int b) { return a + b; }
void greet(const char *name) { printf("Hello, %s!\n", name); }
Pass by Value vs Address
#include <stdio.h>
void by_value(int x) { x = 999; } // doesn't affect caller
void by_address(int *x) { *x = 999; } // modifies caller's variable
int main(void) {
int a = 5, b = 5;
by_value(a); printf("a = %d\n", a); // 5
by_address(&b); printf("b = %d\n", b); // 999
}
Common Pitfalls
- Forgetting to declare functions before use (or missing prototypes).
- Mismatched parameter types between prototype and definition.
- Expecting pass-by-value to modify the caller's variables.
Checks for Understanding
- What happens if you call a function without declaring it first?
- How do you make a function modify a caller's variable?
Show answers
- Compiler error or implicit declaration (dangerous in older C).
- Pass the address and use pointers:
void f(int *p) { *p = ...; }
Practice
- Write a function that calculates the area of a rectangle.
- Write a function that swaps two integers using pointers.
Expected Output
5
Hello, World!
For pass-by-value/address example:
a = 5
b = 999