The 'static' keyword in C ++

I understand that it retains value after exiting the scope (but becomes inaccessible), but I have a few questions.

  • When people say that this is not available outside the scope, does it simply mean that you cannot change the value (it will be erroneous) outside the scope of identification?

  • 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 at each iteration of the loop I set the 'number' variable to 1. As I expected, this was printed 1, 2, 3 .. 10. The compiler recognizes that the line setting it to 1 was a declaration and ignores her "change"?

+5
source share
5 answers

, . . (IINA? い い, な!)

+2

staticExample , . " ", .

#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;
}

:

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

, : " , , . static, , ". , - .

+3

A static variable ( static class) - . , , , - , - - .

: , main() / , . , static , ( C, main()).

/ ( {}).

:

6.7

- , (3.6.2).

, , , , , :

3.7.1

, , , , / , 12.8.

... , static , C - i.e , .

(, ), , .

+1
  • , :

    {
        static int x;
        x = 5;
    }
    x = 6;  // Compiler error here!  We're outside the scope that x was declared in.
    

    , . :

    int *p = NULL;
    {
        static int x;
        x = 5;
        p = &x;
    }
    *p = 6;  // This is fine
    
  • ; , .

0

, , , ( ) , ?

, . " " -, , , . .

, , , , , , .

Your code example = 1has an initializer, not a job. It is used when a variable is initialized, which, since the object is declared static, occurs only the first time that execution passes through the declaration statement.

0
source

All Articles