0

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?

2
  • First you learn to use global variables, then you learn how not to use them, and pass a context variable from function to function, use callback functions, etc. Commented Jul 31, 2014 at 20:34
  • Use correctly by not using at all Commented Jul 31, 2014 at 20:38

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.