September 24th, 2003, 02:30 PM
"Seeing" a variable in one block from another
I'm trying to use a variable that exists in one function, so that I can display it continously to the screen in a display function. Trouble is, because it's local, I can't see it anywhere else in the program. I've tried declaring it at the top so it's global, but I just get a value of 0.0 instead of a continously changing value. Anyone know how to do this? Thanks, ben
September 24th, 2003, 02:57 PM
If you declare a variable at the top of the file outside of any function, then yes it should be visible to all the functions in that file.
Unless a function has a local variable by the same name. In that case, the local variable will "hide" the global variable.
int x; // global variable
x = 2; // changes the global variable
int x; // local variable; hides the global
x = 42; // changes local variable, not the global.
printf("x == %d\n",x); // prints "x == 2"
September 24th, 2003, 04:41 PM
Ah, got ya. So is there any way I can see the changes that are taking place in one function in another function?
September 24th, 2003, 04:52 PM
Local variables are not only 'invisible' outside of the function, they do not exist. Local variables are stored on the stack (or in registers where the compiler performs optimizations); when the function returns, the stack pointer is restored to the position before the function was called, or the registers are re-used.
This is true unless the variable declaration uses the static qualifier, or you are writing a multithreaded app. and the function never exits (by looping indefinately). Unless you are writing a multithreaded application, the value of the variable cannot change unless the function is invoked, in this case, all you need do is return the value, or a pointer to the variable from the function, or get the function to copy its value to some global data.
In C++ you could use a member variable, and either make it public (not recommended), or private and add an access function (better).