Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'static' keyword in C++

Tags:

c++

static

I realize that it retains the value after going out of scope (but becomes inaccessible), but I have a few questions.

  1. When people say it is inaccessible outside of the scope, it just means that you cannot alter the value (it will error) outside of its identifying scope?

  2. I was thinking about this code:

    #include "iostream"
    
    void staticExample();
    
    int main()
    {
        staticExample();
    
        return 0;
    }
    
    void staticExample()
    {
        for (int i = 1; i <= 10; ++i)
        {
            static int number = 1;
            std::cout << number << "\n";
    
            ++number;
        }
    }
    

and I thought to myself, that in every iteration of the loop, I am setting the 'number' variable to 1. As I first expected though, it printed 1, 2, 3.. 10. Does the compiler recognize that the line setting it to 1 was a declaration and ignores its "change"?

like image 314
ZERO Avatar asked Mar 20 '12 22:03

ZERO


1 Answers

Call staticExample twice and see what happens to your output. This will help you understand 'static storage' as it applies to local variables.

#include <iostream> 

void staticExample()
{
    static int number = 1;

    for (int i = 1; i <= 10; ++i)
    {
        std::cout << number << "\n";
        ++number;
    }
}

int main()
{
    staticExample();  // begins counting at 1
    staticExample();  // begins counting at 10

    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

I read a quote once that I liked, "You have stack storage and you have heap storage, but you also have another type of storage. It's called static and it's neither on the stack or in the heap." Not verbatim, but something similar to that.

like image 104
01100110 Avatar answered Oct 04 '22 02:10

01100110