This is allowed:
// scope_1
int i = 100;
if (i > 50)
{
// scope_2
int a = 200;
}
This gives error:
// scope_1
if (100 > 50)
int a = 200;
Is the reason second code example gives us error due to scopes? Thus compiler doesn’t allow for variable a inside particular scope to be declared only if conditional statement evaluates to true, since if it did allow that, then there would be no way for compiler to figure out whether to allow the declaration of another variable named a within scope_1?
Why would you want to do this? Declaring a variable in a one-statement scope where the statement is the variable doesn’t seem to make sense, since you’d never actually have the time to use the declared variable.
The above would result in a conditional variable declaration if you were allowed to reference
aoutside theifstatement. However, declarations cannot be conditional. What could a compiler reasonably do when it encounters an identifier that can be either declared or undeclared? Whichever is the case can only be figured out during run-time, not during compile-time; however the compiler needs to know (because undeclared identifiers are a syntax error), and therefore it will complain about this construct.