Mike Higginbottom

A Digital Garden - frequent growth but a bit weedy in the back corner

Avoid Using Globals For Information Passing

If you’ve run into the classic noob C programmer’s problem of “Why won’t my function update my variable?” then you might have resorted to using a global variable instead of passing the variable into the function as a parameter. Global variables allow ‘write access’ to number from both the caller and the callee, like this:

#include <stdio.h>

int number;

int doubleIt() {
    number *= 2;
}

int main(void) {
    number = 3;
    doubleIt();
    printf("Doubled number is %d", number);
    return 0;
}

but global variables are considered bad for lots of reasons. Not least of which is that your function can no longer double anything other than your specific number.

An improvement is to move number inside main() so it’s no longer global. But then doubleIt() won’t be able to access number. So we need to pass it into doubleIt() as a function parameter. Like this:

#include <stdio.h>

int doubleIt(int number) {
    return number * 2;
}

int main(void) {
    int number = 3;
    doubleIt(number);
    printf("Doubled number is %d", number);
    return 0;
}

That works nicely. And for ‘small’ chunks of data like an int it’s a perfectly standard way to do it. But for ‘larger’ stuff there’s a better way.