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;
}
}
C++ standard allows name hiding, that means that you can declare anything with same identifier in nested scopes.
From N4296:
3.3.10 Name hiding [basic.scope.hiding]
1 item of the list is what you need.
The
x
you are using to print in the last line of your code, belongs toif
block. Thisx
hides the firstx
declared in first line. This is because the scope.According to
C
-...
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 ofif
statement terminates.The second
x
variable has a block scope and is shadowing the previousx
declaration.