1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • This is called "shadowing", you can read about it [here](https://en.wikipedia.org/wiki/Variable_shadowing#C++). – Blaze Sep 12 '19 at 14:06
  • Read up on scope and [block scope](https://en.cppreference.com/w/cpp/language/scope#Block_scope). – Ron Sep 12 '19 at 14:08
  • 3
    `const` has nothing to do with variable lifetime, variables are destroyed at the end of their scope regardless of whether they are `const` or not – Alan Birtles Sep 12 '19 at 14:10

1 Answers1

2

Enlarge your program the following way

#include<iostream>
#include<string>

const std::string s = "a first string";

int main()
{
    std::cout << s << std::endl;

    const std::string s = "a string";
    std::cout << s << std::endl;

    {
        const std::string s = "another string";
        std::cout << s << std::endl;
    }

    std::cout << s << std::endl;
    std::cout << ::s << std::endl;

    return 0;
}

The program output is

a first string
a string
another string
a string
a first string

Each declaration in an internal scope hides a declaration in the outer scope with the same name (except function names that can be overloaded). But the variable declared in the outer scope is still alive. If a variable is declared within a namespace as the first variable s that is declared before main and belongs to the global namespace then you can use its qualified name to access the variable.

When an unqualified name is used then the compiler searches its declaration starting with the nearest scope.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • thank u for ur reply, but, there are still two question that what means "qualified name" and "unqualified name"? another, what means about "::s" in your code? thank u very much!! – liaohuguang Sep 13 '19 at 00:48