CC · Lesson 4 of 8

Functions & Pointers

C functions are straightforward. Pointers less so. But pointers are what make C C, so buckle up.

C
#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 arguments by value — functions get copies. To modify a variable from a function, you must pass a pointer to it. This is the classic "pass by reference" pattern in C.

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;
}
◆ Note
Pointer arithmetic in C is one of its most powerful and dangerous features. We'll keep things simple here — the key insight is that pointers enable passing large data structures efficiently and modifying variables from called functions.