Search

4.3 — Static duration variables

The static keyword is one of the most confusing keywords in the C++ language (maybe with the exception of the keyword “class”). This is because it has different meanings depending on where it is used.

In section 4.2 -- Global variables, you learned that when applied to a variable declared outside of a block, it defines a global variable with internal linkage, meaning the variable could only be used in the file in which it was defined.

The static keyword can also be applied to variables declared inside a block, where it has a different meaning entirely. In section 4.1a -- Local variables and local scope, you learned that local variables have automatic duration, which means they are created when the block is entered, and destroyed when the block is exited.

Using the static keyword on local variables changes them from automatic duration to static duration (also called fixed duration). A static duration variable (also called a “static variable”) is one that retains its value even after the scope in which it has been created has been exited! Static duration variables are only created (and initialized) once, and then they are persisted throughout the life of the program.

The easiest way to show the difference between automatic and static duration variables is by example.

Automatic duration (default):

Each time incrementAndPrint is called, a variable named value is created and assigned the value of 1. incrementAndPrint increments value to 2, and then prints the value of 2. When incrementAndPrint is finished running, the variable goes out of scope and is destroyed. Consequently, this program outputs:

2
2
2

Now consider the static scope version of this program. The only difference between this and the above program is that we’ve changed the local variable value from automatic to static duration by using the static keyword.

Static duration (using static keyword):

In this program, because s_value has been declared as static, s_value is only created and initialized (to 1) once. When it goes out of scope, it is not destroyed. Each time the function incrementAndPrint() is called, the value of s_value is whatever we left it at previously. Consequently, this program outputs:

2
3
4

Just like we use “g_” to prefix global variables, it’s common to use “s_” to prefix static (static duration) variables. Note that internal linkage global variables (also declared using the static keyword) get a “g_”, not a “s_”.

One of the most common uses for static duration local variables is for unique identifier generators. When dealing with a large number of similar objects within a program, it is often useful to assign each one a unique ID number so they can be identified. This is very easy to do with a static duration local variable:

The first time this function is called, it returns 0. The second time, it returns 1. Each time it is called, it returns a number one higher than the previous time it was called. You can assign these numbers as unique IDs for your objects. Because s_itemID is a local variable, it can not be “tampered with” by other functions.

Static variables offer some of the benefit of global variables (they don’t get destroyed until the end of the program) while limiting their visibility to block scope. This makes them much safer for use than global variables.

Quiz

1) What effect does using keyword “static” have on a global variable? What effect does it have on a local variable?

Quiz Answers

1) Show Solution

4.3a -- Scope, duration, and linkage summary
Index
4.2a -- Why global variables are evil

88 comments to 4.3 — Static duration variables

  • diksha chadha

    Hi,

    I have a doubt in the line :
    Static variables offer some of the benefit of global variables (they don’t get destroyed until the end of the program) "while limiting their visibility to block scope". This makes them much safer for use than global variables.

    And in 8.11 it is said : Note that this static member definition is not subject to access controls: you can define and initialize the value even if it’s declared as private (or protected) in the class.

    Could you please explain the difference in the two.

    • Alex

      Two different things entirely. The static variables in this lesson are for non-members, the ones in 8.11 are for static members.

      Non-member static variables are typically defined in a function. They retain their value across function calls, but can't be accessed outside the function.
      Member static variables are defined inside a class. Although normal private or protected members can't be accessed directly from outside the class, a static member definition & initialization can be (but not access beyond that).

  • Dear Great Teacher Mr. Alex and great supporter Mr/Mrs. nascardriver
      
    1) I tried to execute the above program in tutor 4.3 that have a function named incrementAndPrint(); with both static int s_value = 1;(declared as a local variable) and static int g_value = 1;(declared as a global variable ) and i recognized the  program executes  the same output.
    Depend on this fact are we able to conclude  that the effect of static key word  is the same in both local and global(Internal linkage) variable declaration? If we can't what are the reasons?  
    2) This program has also a variable s_value  with static duration and eventually  outputs 2,3 and 4.  Can you explain in more detail how it works? I have tried my best to know about it even by greeting  back to read  the previous sections.B/s i have seen that you are so busy with a lot of questions coming from others.  
    when the 1st incrementAndPrint(); function called it increment the value 1 to 2.what about the out put 3 (2nd function output) Does that mean the value of the first function would copied the value 2 to the secondly called function?
    Did we cover this idea in the previous chapter? where?
    God bless you all!!! You are changing my life indeed!!

    • 1) Static variables behave just like global variables, they're unique to the program.
      2)

      @s_value is only initialized one and maintains it's value across function calls.

      • Dear Mr/Mrs.nascardriver
        Thank you so much for your kind,prompt and clear response . Now i have gotten the point for static variables that they behave just like global variables except they have no linkage like global variables!!!
        And i like the way you clarify my number 2 question.

        I wish God be always with you all !!!
        Thank you indeed!

  • Nux

    Hello,

    I remember you was willing to change std::endl to "\n" in exemple

    The 2 first exemple here use std::endl

  • Hema

    Hello, I was experimenting with the calling functons. I wrote the following code. The compiler says: error:expected primary-expression before 'int'. The error is in line 11.
    Precisely here --> cout<<"x+y= "<< int x()+ int y()<<endl;
                                                            ^

    What does the compiler actually mean and how can I correct it?
    Thanks..

    • nascardriver

      Hi Hema!

      First, let's rename some variables to prevent duplicate names

      The error is still the same, let's look into it.
      You only need to specify the return and parameter types of a function when declaring it. Not when calling it. So when you want to call @x you don't write int.

      Now you're getting another error:

      When you declared @x you decided it should get a parameter (@i). When you call a function the requires parameters you need to pass them in the brackets.

      Your code now compiles and outputs

      Keep on experimenting, it's a good way to learn!

      • Hema

        Can I know why we shouldn't use "using namespace"? The program compiles fine with "using namespace" after removing "int" in line 11.  

        Thanks a lot for the help. 🙂

        • nascardriver

          'using namespace' can lead to naming conflicts. eg. The std namespace has a function called 'min'. This is quite a common name that could occur somewhere else too. You you were 'using namespace std' and called 'min' your compiler wouldn't be able to tell which 'min' you're trying to call.

          Reference
          Lesson 1.8a Naming conflicts and the std namespace

  • Trong Nguyen Van

    I see this is very nice. This static variable isn't destroyed after exiting its scope but we can only access to it in its scope again. In main() or other scope, we can't access it's value!

    Thank you!

  • Hema

    Can you eplain this sentence in more detail-"Static duration variables are only created (and initialized) once, and then they are persisted throughout the life of the program."
    Thanks

    • Alex

      Sure. Normally, if you have a variable defined inside a function (either as a parameter or local variable), that variable is created and destroyed every time the function is executed. There's no persistence. However, with a static variable, the static variable is only created the first time the function is run, and it is not destroyed when the function exits. The next time the function is run, the variable still exists and its previous value has been retained. The static variable is only destroyed at the end of the entire program.

  • felipe

    Is there a super static version of static(that makes the variable value persist even after the program is close?) thanks.

  • Kanwar Ujjwaldeep Singh

    VoidIncrementandPrint
    This Function has no return value,how it send's back value 2 bact to MAIN FUNCTION.
    When main function calls VoidIncrementandPrint, Value is created ,assigned value =1,than incremented and then destroyed at end.But its not sent back to the main Function.Than how it works>

Leave a Comment

Put all code inside code tags: [code]your code here[/code]