C Scope & Lifetime
In this page:
Local Scope
A variable declared inside a function has local scope, meaning it's only visible to code within that same function -- code in other functions has no way to reference it, even by the same name.
Example: Local Scope
#include <stdio.h>
void show() {
int local = 5;
printf("%d", local);
}
int main() {
show();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Global Scope
A variable declared outside of every function has global scope, making it visible to and modifiable by any function in the program -- convenient for shared state, but riskier since any function could change its value unexpectedly.
Example: Global Scope
#include <stdio.h>
int counter = 10;
void show() {
printf("%d", counter);
}
int main() {
show();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Block Scope
Variables declared inside an if block or loop have block scope, meaning they only exist and are only accessible within that specific pair of curly braces, disappearing once execution leaves that block.
Example: Block Scope
#include <stdio.h>
int main() {
if (1) {
int x = 5;
printf("%d", x);
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Variable Lifetime
A variable's lifetime is how long its memory allocation persists during the program's execution -- a local variable's memory is reclaimed automatically the moment its enclosing function returns, and its old value becomes inaccessible.
Example: Variable Lifetime
#include <stdio.h>
void show() {
int x = 5;
printf("%d", x);
}
int main() {
show();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Variable Name Hiding
If a local variable shares a name with a global variable, C lets the local one take precedence inside its own scope, effectively hiding the global's value there -- the global is unaffected and still accessible from other functions.
Example: Variable Name Hiding
#include <stdio.h>
int value = 100;
void show() {
int value = 5;
printf("%d", value);
}
int main() {
show();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: