top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference when a static variable is defined in the function and outside of a function?

0 votes
734 views
What is the difference when a static variable is defined in the function and outside of a function?
posted Jul 3, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

When a static variable is defined in a function, its scope is limited to that function only and it retains its value for multiple calls of it . While the static variable defined outside the function it can be accessed by all the functions defined in the file.

answer Jul 3, 2014 by Rupam
0 votes

When a static variable is defined inside a function that means it is initialized by the zero and life Time of variable is life of the program i.e. there exist even after your block is not in the execution and when the control reaches to same block or function the old value is retained.

Where when the same happen outside of a function that means variable is initialized by zero and has a file scope which means if your process have multiple files then the variable can be used only in the file in which it is defined.

answer Jul 4, 2014 by Salil Agrawal
Hi Salil, Is it necessary that static variable will always be initialized by zero. As far as I know, the statement which initializes static variable is executed once even though function is called multiple times. static varaible can be initialized by any value based on the data type.
Only first time it would be initialized by zero and further on it will not and retain the old value as lifetime of the variable is the lifetime of process.
Similar Questions
+5 votes

You can find three principal uses for the static. This is a good way how to start your answer to this question. Let’s look at the three principal uses:

  1. Firstly, when you declare inside of a function: This retains the value between function calls

  2. Secondly, when it is declared for the function name: By default function is extern..therefore it will be visible out of different files if the function declaration is set as static..it will be invisible for outer files

  3. And lastly, static for global parameters: By default you can use global variables from outside files When it’s static global..this variable will be limited to within the file.

is this right ?

+3 votes

As per my understanding uninitialized static variable is stored in BSS and initialized static variable is stored in DS, then what about the variable which is initialized with 0 ? where it will be stored BSS/DS?

...