Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why does the following code compiles, under g++, with out any warning or error? The problem I see is that the variable x defined in the first line is accessible inside the if scope but in spite that it's redefined again.

int main() {
    int x = 5;
    std::cout << x;
    if (true) {
        int x = 6;
        std::cout << x;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
353 views
Welcome To Ask or Share your Answers For Others

1 Answer

According to C-

6.2.1 in C99:

If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the } that closes the associated block

...

If an outer declaration of a lexically identical identifier exists in the same name space, it is hidden until the current scope terminates, after which it again becomes visible.

In both C and C++ it is legal for the same name to be used within multiple scopes.

So in your code the previous i remains hidden till the scope of if statement terminates.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...