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; }
extern,static,register,autohave different meanings, onlystaticandexterntalk about storage (both of which imply static storage).autoceased to be such with C ++ 11 and is now used for other purposes,registerno longer used. But addedthread_local. The variableiwill 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