#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    55
    Rep Power
    12

    "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
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,162
    Rep Power
    2222
    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.

    Code:
    int x;   // global variable
    
    void foo1(void)
    {
        x = 2;   // changes the global variable
    }
    
    
    void foo2(void)
    {
        int x;  // local variable; hides the global
    
        x = 42;   // changes local variable, not the global.
    }
    
    int main(void)
    {
        foo1();
        foo2();
        printf("x == %d\n",x);  // prints "x == 2"
    
        return 0;
    }
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    55
    Rep Power
    12
    Ah, got ya. So is there any way I can see the changes that are taking place in one function in another function?
  6. #4
  7. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,110
    Rep Power
    1803
    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).

    Clifford

IMN logo majestic logo threadwatch logo seochat tools logo