Static Variables

E

Eirik WS

What's the use in static variables, like 'static int INTEGER' or 'static
char CHARACTER'?
 
M

Mark A. Odell

What's the use in static variables, like 'static int INTEGER' or 'static
char CHARACTER'?

At file scope it makes the variable "private" to that file (module). When
used in block scope it changes the variables life-time from temporary to
"always there". Of course file scoped static variables also have program
duration life time but static, in that case, is not the reason why.
 
W

Wolfgang Kaufmann

* Thus spoke Eirik WS <[email protected]>:

Hallo,
What's the use in static variables, like 'static int INTEGER' or
'static char CHARACTER'?

| #include <stdio.h>
|
| void my_static_function()
| {
| static int num = 0;
| printf("value of num is %d. \n", ++num);
| }
|
| int main(int argc, char **argv)
| {
| int count = 10;
| while(count--)
| my_static_function();
| return 0;
| }

....will print:

| value of num is 1.
| value of num is 2.
| value of num is 3.
| value of num is 4.
| value of num is 5.
| value of num is 6.
| value of num is 7.
| value of num is 8.
| value of num is 9.
| value of num is 10.


Wolfgang.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,135
Messages
2,570,783
Members
47,341
Latest member
hanifree

Latest Threads

Top