Static Variables in C++

What does static mean in C?

  1. A static variable inside a function keeps its value between invocations.
  2. A static global variable or a function is "seen" only in the file it's declared in

(1) is the more foreign topic if you're a newbie, so here's an example:

#include <stdio.h>

void foo()
{
int a = 10;
static int sa = 10;

a += 5;
sa += 5;

printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
int i;

for (i = 0; i < 10; ++i)
foo();
}

This prints:

a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60

This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

Quoting Wikipedia:

In the C programming language, static
is used with global variables and
functions to set their scope to the
containing file. In local variables,
static is used to store the variable
in the statically allocated memory
instead of the automatically allocated
memory. While the language does not
dictate the implementation of either
type of memory, statically allocated
memory is typically reserved in data
segment of the program at compile
time, while the automatically
allocated memory is normally
implemented as a transient call stack.

And to answer your second question, it's not like in C#.

In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

How do static variables in C persist in memory?

static variables and other variables with static storage duration are stored in special segments outside the stack. Generally, the C standard doesn't mention how this is done other than that static storage duration variables are initialized before main() is called. However, the vast majority of real-world computers work as described below:

If you initialize a static storage duration variable with a value, then most systems store it in a segment called .data. If you don't initialize it, or explicitly initialize it to zero, it gets stored in another segment called .bss where everything is zero-initialized.

The tricky part to understand is that when we write code such as this:

void func (void)
{
static int foo = 5; // will get stored in .data
...

Then the line containing the initialization is not executed the first time the function is entered (as often taught in beginner classes) - it is not executed inside the function at all and it is always ignored during function execution.

Before main() is even called, the "C run-time libraries" (often called CRT) run various start-up code. This includes copying down values into .data and .bss. So the above line is actually executed before your program even starts.

So by the time func() is called for the first time, foo is already initialized. Any other changes to foo inside the function will happen in run-time, as with any other variable.

This example illustrates the various memory regions of a program. What gets allocated on the stack and the heap? gives a more generic explanation.

c programming using a static variable and then pointing to it ? possible?

This is valid code.

A static variable, whether declared at file scope or inside of a function, has full program lifetime. That means its address will always be valid and can be safely dereferenced at any point in the program.

Why declare a static variable in main?

Unless you're doing something very non-standard such as calling main directly, there's little point in declaring local variables static in main.

What it is useful for however is if you have some large structure used in main that would be too big for the stack. Then, declaring the variable as static means it lives in the data segment.

Being static also means that, if uninitialized, the variable will be initialized with all 0's, just like globals.

C simple static variable behaviour mystery

When you declare a static variable inside a function instead of outside a function it can only be accessed inside the function. Otherwise it works like a global variable in the sense that it exists throughout the lifetime of the program. Its initial value is determined when the program is compiled so it must be initialized with a constant expression. Any decent compiler should warn you if the initializer is not constant as in your example:

$ gcc -o test -Wall test.c
test.c: In function ‘sum’:
test.c:3:24: error: initializer element is not constant
static int sum =0+num;
^

Note that you should always compile your C programs with warnings enabled.

C static variables initialization

This (statics/globals) is where an initializing definition is really different from an uninitialized definition followed by an assignment.
Historically, the former even used to have different syntax (int count /*no '=' here*/ 0;).

When you do:

int fun() {
static int count = 0;
//...
}

then except for the different scopes (but not lifetimes) of count, it's equivalent to:

static int count = 0; //wider scope, same lifetime
int fun() {

//...
}

In both cases, the static variable becomes initialized at load time, typically en-masse with other statics and globals in the executable.



Related Topics



Leave a reply



Submit