Variable declaration

Discussion in 'C' started by kanaks_go4ex, Aug 26, 2008.

  1. kanaks_go4ex

    kanaks_go4ex New Member

    Joined:
    Jun 11, 2008
    Messages:
    16
    Likes Received:
    0
    Trophy Points:
    0
    Let's consider as below,

    // For the Global Scope only
    // All declaration Not local inside a fucntion
    int *ptr;
    int i_val;

    static int st_val ;
    static int *st_ptr;

    what is main difference for the declaration of the variable with / without static type?

    What will be the default value stored for all the four declarations ?

    For all the above 4 ,by default for the pointer declaration will this store as NULL or Junk ? normal variable will store Zero or junk values ?

    -thanks
     
  2. jamsheedm

    jamsheedm New Member

    Joined:
    Aug 25, 2008
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Static variable out side function have file scope and life time through out the program.
    i.e static variable will be accessible in the file its declared ,but u can access it from any where by using pointers.
    also static variables are allocated from .bss and is initialized to zero at start of execution.

    all will be allocated from .bss and will be initialized to zero.
     
  3. oogabooga

    oogabooga New Member

    Joined:
    Jan 9, 2008
    Messages:
    115
    Likes Received:
    11
    Trophy Points:
    0
    At the global scope all of your examples will zero the variables. The only difference is that the "static" variable will not be visible from other program files, i.e., you could not in another file access the "st_val" variable with a statement like "extern int st_val" whereas you could access "i_val" that way.

    The reason the variables are zeroed is that any memory allocated to your process is initially zeroed. So any variable not stored on the stack (and therefore with a permanent location) will start out zeroed. The reason stack variables have "junk" in them is that they are sharing space with previous (now deallocated) stack variables. Dynamically allocated memory can also be re-used so may also have junk in it.

    As for pointers, since NULL is basically zero, they start out NULLed.

    As jamsheedm said, it would be possible to access the contents of st_val from another program file with a pointer, either itself global (and non-static) or passed to a subroutine in the other file.
     

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