What this keyword really does?
I read somewhere it makes vars file-scope. And somewhere else I heard it makes vars to live even after the end of the block.
Now, what is the right explanation? :confused:
Printable View
What this keyword really does?
I read somewhere it makes vars file-scope. And somewhere else I heard it makes vars to live even after the end of the block.
Now, what is the right explanation? :confused:
Both
It makes vars filescope even if it is used in a block?
Depends on if you declare it within that block of code, or outside of any function block (similar to how a basic global is declared). Declared within a function for example the value of the static variable will persist between function calls and be visible (in scope) within that function. Declared outside of any function (as globals are) it makes the variable have file scope (like a global but only to that source file/translation unit and not visible to other files via the use of the extern keyword).Quote:
Originally Posted by siavoshkc
So it has really two meanings.
That's true, but the static var is not accessible outside the block. So, this doesn't work:Quote:
And somewhere else I heard it makes vars to live even after the end of the block.
Hmmm...so what good is a static variable? How do you get back inside a block to access the static var after you have exited the block? Ahah! A function can enter and exit a block more than once:Code:#include <iostream>
using namespace std;
int main()
{
{
static int num = 10;
}
cout<<num<<endl;
return 0;
}
Code:#include <iostream>
using namespace std;
void myFunc()
{
static int num = 0; //only executed the first time through the function
++num;
cout<<num<<endl;
}
int main()
{
myFunc(); //1
myFunc(); //2
return 0;
}
Understood. If we use static in functions (any block) the value of var wont be changed between the calls.
That's right. It means static vars are good for saving information between class instances too.
Note that the second meaning, (file scope) is deprecated in C++ in favor of using an unnamed namespace.
As noted in the link above, the static keyword is also used with classes/structs to indicate that a member variable will have only one instance shared across all instantiations of the class, and similarly a member function does not have a this pointer and cannot access the data of any particular instantiation.
Let me read the link, then I'll come back.
OK, tnx.