how can we use static and extern?and where can we use this?
Answer Posted / pramod
static storage class is used for the following situations
1) the variable is defined as static within a function and
we can call the function several times, but we want that the
function should initialize the variable only once that is
during the first call to that function.So the variable will
stay alive in different calls to this function
2)In C++ , if we want a common variable between all the
objects( like a counter for how many objects have been
created) then static is allocated as it is not attached to
any object but class
extern storage is for global variables
1)if we want one varibale to be available to all the
functions in our program, make the varibale as global
variable( extern storage), it will be accessed by all the
functions in that file.But avoid declaring variable as
global for security reasons( can be accessed from any other
file in the PATH) and memory reasons (global variables are
deallocated only when the entire program terminates).
2)if we declare a variable in a file as extern , then
compiler will assume that this variable is not defined in
the present file but in some other file.So while compiling
there won't bw any error but error will come at the linking
if the extern variable is not present in the refernced files.
There is one special case
static global variable
we want a variable to be global , means accessible to all
the functions in that file and want that the variable should
not be accessible to any other file, just to make it static
global variable.So the visibility of that variable becomes
file specific only.
| Is This Answer Correct ? | 3 Yes | 1 No |
Post New Answer View All Answers
What are the types of data files?
What does stand for?
Explain data types & how many data types supported by c?
What does d mean?
what is associativity explain what is the precidence for * and & , * and ++ how the folloing declaration work 1) *&p; 2) *p++;
What are data structures in c and how to use them?
Explain what is the best way to comment out a section of code that contains comments?
How many types of arrays are there in c?
What is volatile c?
Differentiate abs() function from fabs() function.
What is || operator and how does it function in a program?
What is the difference between the local variable and global variable in c?
Function which gives a pointer to a binary trees const an integer value at each code, return function of all the nodes in binary tree.?
Is null always equal to 0(zero)?
What is the best way to store flag values in a program?