
Scope in C
? Scope in C
Scope in C refers to the visibility and lifetime of variables — i.e., where a variable can be accessed in your code.
There are 4 types of scope in C:
? 1. Block Scope (Local Scope)
Variables declared inside a block (like in functions or {}
) are accessible only within that block.
() { int x = 10; // x has block scope printf("%d", x);}
x
is local tomyFunction()
Cannot be accessed outside the block
? 2. Function Scope
Applies to labels (used with goto
) inside a function. Rarely used.
void func() { goto label; label: printf("Hello\n");}
? 3. File Scope (Global Scope)
Variables declared outside all functions are global — accessible anywhere in the file after declaration.
int count = 0; // global variablevoid display() { printf("%d\n", count); // accessible here}
? 4. Function Prototype Scope
In function declarations:
void fun(int a); // `a` is only known inside this declaration
This a
only exists for declaration purposes.
? Storage Class Keywords & Scope
Keyword | Scope | Lifetime |
---|---|---|
auto | Local | Inside block |
register | Local | Inside block |
static | Local or global | Entire program (retains value) |
extern | Global | Refers to external variable |
?? Tips
? Keep variables local if possible — it avoids bugs.
? Use
static
inside functions if you need the value to persist between calls.? Avoid unnecessary global variables.