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?
-
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.Cloud– Cloud2014-07-31 20:34:42 +00:00Commented Jul 31, 2014 at 20:34
-
Use correctly by not using at allDavid Heffernan– David Heffernan2014-07-31 20:38:54 +00:00Commented Jul 31, 2014 at 20:38
Add a comment
|
1 Answer
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
}