Course contentsShow
← C
Lesson 492 of 1,2197. PointersFree lesson

Side effects in pointer-based functions

Side effects in pointer-based functions

What you'll learn: How passing pointers allows functions to create "side effects" that permanently modify variables outside their own scope.

The "Remote Control" Effect

In previous lessons, you learned that C usually passes arguments by value—meaning the function gets a temporary copy of your data. If you change that copy, the original stays the same. However, when you pass a pointer, you aren't giving the function a copy of the data; you are giving it the address of the original data.

Think of it like a remote control. If you give someone a copy of a DVD, they can scratch it or draw on it, and your DVD at home remains perfect. But if you give them a remote control to your TV, they can change the channel from across the room. That change is a "side effect"—an action that persists even after they put the remote down.

Why Side Effects Matter

In C, we use these side effects intentionally when we want a function to update more than one value, or when we want to avoid the overhead of copying large amounts of data. By accepting a pointer, a function gains the "permission" to reach back into the caller's memory and overwrite what is there.

#include <stdio.h>

// This function has a side effect: it modifies the caller's variable
void levelUp(int *levelPtr) {
    *levelPtr = *levelPtr + 1; // Reaching into the address to change the value
    printf("Leveling up inside the function...\n");
}

int main() {
    int myPlayerLevel = 5;

    printf("Before: %d\n", myPlayerLevel);

    // We pass the address of our variable
    levelUp(&myPlayerLevel);

    // The 'side effect' remains even though the function is finished
    printf("After: %d\n", myPlayerLevel); 

    return 0;
}

Controlling the Power

Because side effects are permanent, they are powerful but dangerous. If a function modifies a pointer-based argument by mistake, the rest of your program will be working with corrupted data. When you see a * in a function’s parameter list, it is a signal: "Warning: This function has the power to change the variables I pass to it."

Key takeaway

Side effects occur when a function uses a pointer to modify a variable in the caller’s scope, allowing changes to persist after the function ends.