Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
int main() {
int level = 1;
{
int level = 2;
std::cout << level << ' ';
}
std::cout << level << '\n';
}2 1
- Expecting
2 2:int level = 2;declares a new variable that lives only until the closing brace; the outerlevelis never changed and keeps1. - Expecting a compile error: a name cannot be declared twice in one block, but an inner block may declare it again and hide the outer one.
- What would the program print if the inner line were
level = 2;instead? - How does the compiler warning flag
-Wshadowhelp you catch a hidden variable?