Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Variable declaration (http://www.go4expert.com/forums/variable-declaration-t13304/)

kanaks_go4ex 27Aug2008 00:43

Variable declaration
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 ?


jamsheedm 27Aug2008 01:25

Re: Variable declaration
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.

oogabooga 27Aug2008 01:33

Re: Variable declaration
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.

All times are GMT +5.5. The time now is 15:37.