Lesson 4 of 12
Functions & Pointers
Learn how to write and get a first look at , which C uses to let functions change data they are given.
#include <stdio.h>
// Function declaration (prototype) — tells compiler about the function
int add(int a, int b);
double average(int arr[], int len);
int main() {
printf("%d\n", add(3, 4)); // 7
int data[] = {5, 10, 15, 20};
printf("%.1f\n", average(data, 4)); // 12.5
// Pointers — a variable that holds a memory address
int x = 42;
int *p = &x; // p points to x; & is "address of"
printf("Value of x: %d\n", x); // 42
printf("Address of x: %p\n", &x); // some address
printf("Value via p: %d\n", *p); // 42 — * is "dereference"
*p = 100; // change x through the pointer
printf("x is now: %d\n", x); // 100
return 0;
}
// Function definitions
int add(int a, int b) {
return a + b;
}
double average(int arr[], int len) {
int sum = 0;
for (int i = 0; i < len; i++) {
sum += arr[i];
}
return (double)sum / len; // cast to double before dividing
}C passes by value — functions get copies. To modify a from a function, you must pass a pointer to it. This is the classic "pass by reference" pattern in C.
#include <stdio.h>
// Swap using pointers — pass by reference
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Return pointer to array (careful: must be static or heap-allocated)
int* make_range(int n) {
static int arr[100]; // static — lives beyond function call
for (int i = 0; i < n; i++) arr[i] = i;
return arr;
}
// Function pointer
int (*operation)(int, int); // pointer to a function taking two ints
int multiply(int a, int b) { return a * b; }
int subtract(int a, int b) { return a - b; }
int main() {
int x = 5, y = 10;
printf("Before: x=%d, y=%d\n", x, y);
swap(&x, &y); // pass addresses
printf("After: x=%d, y=%d\n", x, y); // swapped!
// Use a function pointer
operation = multiply;
printf("3 * 4 = %d\n", operation(3, 4)); // 12
operation = subtract;
printf("10 - 3 = %d\n", operation(10, 3)); // 7
return 0;
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.