Home > Net >  Static Variable Concepts 'C'
Static Variable Concepts 'C'

Time:12-22

After I have read about static variable, something confuses me. We can say the keyword static acts to extend the lifetime of a variable to the lifetime of the program because the lifetime of a variable is the period over which it exists.

My question are:

  1. What really happens inside?
  2. Is memory allocated specifically for this variable or it is a kind of pointer?

i have read from differente ressources

CodePudding user response:

In a C program, the static keyword is used to declare a variable, a pointer or a function as having static storage duration. This means that the variable, the pointer or the function is allocated memory at the time the program is compiled, and the memory is not released until the program terminates.

A variable, a pointer or a function with static storage duration is only visible within the file in which it is defined, and is not visible to code in other files. This can be useful for creating variables or functions that should not be accessible from other parts of the program.

CodePudding user response:

We can say the keyword static acts to extend the lifetime of a variable to the lifetime of the program because the lifetime of a variable is the period over which it exists.

This is true for static variables defined inside a function like:

int *my_function() {
     static int my_static_var[4] = {0,0,0,0};

     return my_static_var;
}

Here my_static_var never goes out of scope, so it's valid to access the memory after the function has returned.

However, all calls to this (my_function) function will return the exact same block of memory, so conceptually it's really a global variable that can't be accessed directly outside of the function.

Of course, you can also define variables outside a function:

static int my_static_var[4]; 

Here my_static_var is only accessible within the same translation unit.

That means another "file" cannot access my_static_var, its bound to the file it was defined.

Also all globally defined variables are all automatically initialized to 0

Note you cannot declare a static variable, since static variables are intentionally not shared with other parts of your source code. You always have to define (declaration / definition are two different things) it.

The same concept can be applied to static functions:

static int my_function() {
    return 0;
}

Here the function my_function cannot be accessed outside the translation unit it was defined in.

I don't know of any other uses for the static keyword in C.

¹ I'm not sure if this applies to static variables inside a function.

  •  Tags:  
  • c
  • Related