Why does this work?

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.
Thanks filipe, that makes sense. I just tried out what you said by writing this:
1
2
3
4
5
6
7
8
9
int main()
{
	{string s = "a string";
	cout << s << endl;
	{string s = "another string";
	cout << s << endl;}
	cout << s << endl;}
	return 0;
}


and the result shows that the first s is left as it was.


a string
another string
a string


Can you please be more specific about what you said about how "Inside the inner scope, you can't talk about the outer s"?

this:

1
2
3
4
5
6
int main()
{
	{string s = "a string";
	{cout << s << endl;}}
	return 0;
}


still prints

a string




I meant in that case, where you had a local s clouding the outer one.
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.
Last edited on
Interesting. Thanks for the info Intrexa and filipe.
Topic archived. No new replies allowed.