I realize that it retains the value after going out of scope (but becomes inaccessible), but I have a few questions.
When people say it is inaccessible outside of the scope, it just means that you cannot alter the value (it will error) outside of its identifying scope?
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 in every iteration of the loop, I am setting the 'number' variable to 1. As I first expected though, it printed 1, 2, 3.. 10. Does the compiler recognize that the line setting it to 1 was a declaration and ignores its "change"?
Call staticExample twice and see what happens to your output. This will help you understand 'static storage' as it applies to local variables.
#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;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
I read a quote once that I liked, "You have stack storage and you have heap storage, but you also have another type of storage. It's called static and it's neither on the stack or in the heap." Not verbatim, but something similar to that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With