In C, **Scope** refers to the part of the program where a variable is defined and can be used. Every variable has a specific boundary. This boundary ensures that variables are only used where they are intended, protecting data from being accidentally modified by other parts of the code.
Variables declared inside a function or a block { ... } are called **Local Variables**. They can only be accessed by statements that are inside that specific function or block.
Variables declared outside of all functions (usually at the top of the program) are called **Global Variables**. They are accessible from any part of the program, including inside any function.
Variables used as arguments in the function definition are treated as local variables within that function. They have **Formal Parameter Scope**. They exist only during the execution of that specific function call.
| Feature | Local Variable | Global Variable |
|---|---|---|
| Declaration | Inside a function/block. | Outside all functions. |
| Accessibility | Only within that function. | Everywhere in the program. |
| Life Period | Function execution time. | Program execution time. |
| Storage | Stack memory. | Data segment memory. |
What happens if a local variable has the same name as a global variable? In C, the Local variable takes precedence. This is called "Shadowing." The function will use its own local version and ignore the global one.
A static local variable is a special hybrid. It has the scope of a local variable (only visible in its function) but the lifetime of a global variable (it remembers its value even after the function ends).