What does static variable mean?

Posted on

The *static* variable will remember its value even when you go out of scope. The *static* variables are not created on stack frame of the function. The static variables are kept in the data segment in executable. The name has no significance for *static* variables. In a same file, you can have multiple *static* variables with the same name in different blocks. The compiler will replace these names with starting address of data segment (_DATA) + offset.

In following function, static_variable will be initialized to 1 and it will be incremented by 1 on each invocation.

int static_counter()

{

static int static_variable = 1;

static_variable++;

return static_variable;

}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s