Course contentsShow
← C
Lesson 251 of 1,2194. Control FlowFree lesson

Variable scope inside if-else blocks

Variable scope inside if-else blocks

What you'll learn: You will understand how variables created inside an if or else block are invisible to the rest of your program.

The "Room" Analogy

Think of a pair of curly braces { } as a private room. When you create a variable inside these braces, it’s like placing a physical object in that room. You can use it freely as long as you are inside, but once you step out the door (the closing brace }), that room—and everything inside it—ceases to exist.

In C, this is called block scope. A variable is only "alive" within the specific block where it was born.

Seeing the boundary

It is a common mistake to calculate a value inside a branch and try to use it later. Look at how the compiler treats these variables:

#include <stdio.h>

int main() {
    int age = 20;

    if (age >= 18) {
        // This variable is local to the 'if' block
        int membership_fee = 50;
        printf("Adult fee: $%d\n", membership_fee);
    } else {
        // This variable is local to the 'else' block
        int membership_fee = 10;
        printf("Junior fee: $%d\n", membership_fee);
    }

    // ERROR: The compiler can't see 'membership_fee' here.
    // It "died" the moment we hit the closing brace above.
    // printf("Total due: %d", membership_fee); 

    return 0;
}

In the example above, the two membership_fee variables are actually two different people with the same name living in different houses. They don't know each other, and the main function doesn't know either of them once the if-else structure finishes.

How to "save" data

If you need a value to survive after the if-else block ends, you must announce its existence before the block starts. By declaring the variable in the outer scope (the main function's body), the branches can modify it, and the value will stick around after the closing brace.

If you find yourself getting an "undeclared identifier" error, check your braces. You likely tried to grab something from a room that is already locked and gone.

Key takeaway

Variables declared inside curly braces are local to that block and cannot be accessed once the block ends.