Why can’t variables be declared in an if statement?

Variables can be declared inside a conditional statement. However you try and access b in a different scope.

When you declare b here:

if(a == 1) {
    int b = 0;
}

It is only in scope until the end }.

Therefore when you come to this line:

b = 1;

b does not exist.

Leave a Comment