Difference b/w global and static global variable

Discussion in 'C' started by rsodimbakam, Sep 22, 2008.

  1. rsodimbakam

    rsodimbakam New Member

    Joined:
    Sep 19, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    Is there any difference b/w global variable and static global variable ? and when each one is used in real time environement ?

    Thanks
    Kiran
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Global variable defined with static keyword has a scope limited to translation unit it is defined in. This variable is not "totally" global (possible to use in other source files), it is visible and usable only in this source file (translation unit, to be exact).
     
  3. internet_bug

    internet_bug New Member

    Joined:
    Sep 16, 2008
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    Static variables are those which are initilaized and defined inside the main() body. These variables can be re-initialied as per requirement and their value changes. On the other hand Global variables are initilaized and defined before the main() body. If you initilialize and define a varibale gloabally it's value will remain constant, meaning whenever you use this variable in your main() body its value used will be the defined value before the main() body . Hope u got that
     
  4. erislover

    erislover New Member

    Joined:
    Aug 5, 2008
    Messages:
    9
    Likes Received:
    0
    Trophy Points:
    0
    static is a storage class specifier (static, auto, register, extern). Global variables (those defined outside a function body) without an explicit storage class are always static, but global variables not specifically declared static have external linkage.

    Confusing?
    Code:
    static int i; // available anywhere in this file (translation unit)
    int j; // available anywhere in this file, and in other files by those files using "extern"
    extern int k; // available anywhere in this file, but actually declared in some other file;
    
    void main(void)
    { // ...
    }
    If you have no good reason to allow external linkage, I suggest you explicitly declare global variables to be static. Furthermore, I suggest avoiding global variables unless you have no good alternative. (You may not have a good alternative, especially in embedded systems, given your mention of RTS).
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice