What is the essence of each specifier? And why in this code I can not access the variable i , since by definition static keeps the value to the end of the program in memory. And how do I use static count the number of times the function was called?

Code:

 #include "stdafx.h" #include <iostream> using namespace std; int foo() { static int i = 0; i++; return i; } int main() { foo(); cout << i; system("pause"); return 0; } 
  • The keywords extern , static , register , auto have different meanings, only static and extern talk about storage (both of which imply static storage). auto ceased to be such with C ++ 11 and is now used for other purposes, register no longer used. But added thread_local . The variable i will actually hold the value to the end of the program, but its scope is limited to the function in which it is declared. But to address it directly does not make much sense, so you still return its value. cout << foo(); - VTT

1 answer 1

In C ++, there are no register and auto storage specifiers for a long time. The storage thread_local in C ++ are reduced to: static , thread_local , extern and mutable .

Direct access to a variable in C ++ is done through its identifier - the name. A variable can be accessed by its "short" identifier only from within the scope of this identifier. Also with the help of the operator :: you can access identifiers in other scopes. However, the operator :: does not allow access to identifiers declared locally. In your case, i declared locally, i.e. is visible only inside the foo function, so you cannot access i outside of foo .

The fact that " static keeps the value to the end of the program" on the visibility of the identifier i does not matter at all: the lifetime of the object and the scope of its identifier are completely independent concepts.

"How using static to count how many times a function was called" is actually perfectly illustrated by your example.

 int main() { cout << foo() << endl; cout << foo() << endl; cout << foo() << endl; cout << foo() << endl; } 
  • Once again, you surprise with new words :) "access" ... - αλεχολυτ