I am currently working through the book "Accelerated C++" and I've come across an example that I don't understand. The example given is supposed to make the reader have a better understanding of local variables and their lifespan within curly braces. However this one example goes against my understanding of how this works.
The example is:
1 2 3 4 5 6 7 8
int main()
{
{ const string s = "a string";
cout << s << endl;
{ const string s = "another string";
cout << s << endl; }}
return 0;
}
In the book it says that a local variable only exists within a set of curly braces, and is destroyed once it reaches the }. In this example, const string s is initialized again within another set of curly braces before the end of the first set of curly braces. Why is it that when I compile this, it prints:
a string
another string
should this happen? Or should there be an error? If a local variable is destroyed once it reaches the last curly brace, then wouldn't the initialization of const string s in the second set of curly braces attempt to overwrite the original const string s? I am using microsoft visual studio 2010.
There are two different variables there. The outer s still exists when the inner s is declared. Inside the inner scope, you can't talk about the outer s, though.
It keeps stepping up scopes until it finds a valid variable. Note that functions won't do that tho. It's bad practice tho to have multiple variables named the same thing and to rely on that.