I'm beginner in C++. I learned from the book "accelerated c++" about a const variable inside a block scope. It means that the "const variable will be destroyed when the scope ends at }
.
But in the test: the const string variable s
is defined inside the first block. In the second block, the s
is also defined. When the second s
is printed out the first block's s
hasn't been destroyed.
I think the program is invalid, but the result is totally true when I compile the program. I don't known why it is. please help me to understand the code.
#include <iostream>
#include <string>
int main()
{
const std::string s = "a string";
std::cout << s << std::endl;
{
const std::string s = "another string";
std::cout << s << std::endl;
}
return 0;
}
the result is
a string
another string