I have finally come across the static keyword in C/++. From what I understand, using the static keyword on a variable declared inside a function makes it so other functions cannot access the variable, but here's the part I don't understand: IT'S ALREADY A LOCAL VARIABLE. I get the purpose of the keyword in the global scope (preventing other files from accessing the variable), but I just don't see the purpose of it in the local scope. Another thing I don't get is using the keyword inside a C++ class. (In C++ classes, ) What's the difference between private and static variables?? Could someone point me in the right direction by clearing up my murky definitions of these concepts? Thanks! (Also what is the purpose of a static function and how can I implement one?)
Asked
Active
Viewed 44 times
0
-
I'm sure your book explains what the keyword does? Which book are you using? – Asteroids With Wings May 03 '20 at 19:56
-
4No, `static` on a local variable has nothing whatsoever to do with access by other functions. It changes the variable's [*duration*](https://en.cppreference.com/w/c/language/static_storage_duration). Normally, local variables are initialized from scratch every time the function is called, and destroyed when it returns. `static` local variable is initialized when the function is called for the first time, and destroyed at the end of the program. They preserve their value between calls of that function. – Igor Tandetnik May 03 '20 at 19:56
-
@AsteroidsWithWings I am learning through reading documentation and articles and occasionally watch youtube videos – Serket May 03 '20 at 19:58
-
@IgorTandetnik thanks!! – Serket May 03 '20 at 19:58
-
The `static` keyword is heavily overloaded and means very different things in different contexts. `static` on a global varible changes its linkage; static on a local variable changes its duration; static on a data member or member function means yet third thing. – Igor Tandetnik May 03 '20 at 19:58
-
What do you mean by __static on a data member or member function means yet third thing__? – Serket May 03 '20 at 19:59
-
I think that would be a misuse of static (since no variable can be extern static other function cannot acess it, but static keyword isn't intended to be used like that) – user12986714 May 03 '20 at 19:59
-
@IgorTandetnik If you would upload an organised answer with all three definitions with examples I'll mark it as correct for future users. – Serket May 03 '20 at 20:01
-
@Serket That's the problem then! You cannot learn C++ like that. [Here ya go](https://stackoverflow.com/q/388242/4386278) – Asteroids With Wings May 03 '20 at 20:03
-
a static member is a member of the class, not a member of an instance – bruno May 03 '20 at 20:03
-
https://en.wikipedia.org/wiki/Static_%28keyword%29#Static_local_variables – Asteroids With Wings May 03 '20 at 20:04
-
For good measure: https://en.cppreference.com/w/cpp/keyword/static – Igor Tandetnik May 03 '20 at 20:15