Why can't we declare variables in if statement?

if ( int i ) => int i is not a boolean expression, so this won’t work.

if ( booleanExpr ){
  int a = 5;
...
}

here a is a local variable within the if block. At the end of the if-block, it is removed from the stack and becomes unusable.

int a = 5;
if ( booleanExpr){
  ...
}

Here a is not local to the if block, but to the containing method. So, it will be on the stack during the entire execution of the method (starting from its declaration).

a could also be an instance or static variable to the class, then it’s accessible in every method of the class (instance variables are not accessible in a static context, though)

Browse More Popular Posts

Leave a Comment