In your second example it's not just a "declaration with initialization": you are declaring and initialising inside the inner scope of the if
branch and the else
branch.
int main(int argc, char *argv[])
{
// SCOPE A
if (argc == 2) {
// SCOPE B
char* str = "Two";
}
else {
// SCOPE C
char* str = "Not two";
}
my_print(str);
}
So you have three different scopes. You are trying to use a variable that does not exist in the scope you are using it. To have a code that does not raise a compile-time error you should use this following code:
int main(int argc, char *argv[])
{
// SCOPE A
if (argc == 2) {
// SCOPE B
char* str = "Two";
my_print(str);
}
else {
// SCOPE C
char* str = "Not two";
my_print(str);
}
}
As mentioned: "The variable is local to the scope where it's declared"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…