Theodcyning
Theodcyning

Reputation: 23

How to use global variables in C to use the same variable in different functions

I'm new to c, and I'm trying to figure out how to use global variables. If I define one in main the variables come up as undefined in the other function, but if I define it outside all functions all variables that I wanted global are undefined. Any tips on how to use them correctly?

Upvotes: 0

Views: 1287

Answers (1)

chris
chris

Reputation: 5006

You define them above main, under your includes:

#include <stdio.h>

int foo;
char *bar;

void changeInt(int newValue);

int main(int argc, char **argv) {
    foo = 0;
    changeInt(5);
    printf("foo is now %d\n", foo);
    return 0;
}

void changeInt(int newValue) {
    foo = newValue;
}

As an aside, its not best practice to use globals, especially in multithreaded stuff. In some applications its perfectly fine, but there is always a more correct way. To be more proper, you could declare your variables you need in main, then give functions that modify them a pointer to it.

ie.

void changeInt(int *toChange, int newValue);

int main(int argc, char **argv) {
    int foo = 0;
    changeInt(&foo, 5);
    printf("foo is now %d\n", foo);
    return 0;
}

void changeInt(int *toChange, int newValue) {
    *toChange = newValue; // dereference the pointer to modify the value
}

Upvotes: 2

Related Questions