Nearby lessons

50 of 72

C - Scope

Scope is the region of a program where a variable can be used. This lesson focuses on the two everyday scopes: local scope (a variable declared inside a function) and global scope (a variable declared outside every function).

Local Scope — Variable Inside a Function

A variable declared inside a function is local to that function. It comes into existence when the function is called and disappears when the function returns. No other function can see or use it.

Example01
CCode Cell
1#include <stdio.h>
2 
3void showLocal(void)
4{
5 int local = 10; /* local to showLocal */
6 printf("local = %d\n", local);
7}
8 
9int main()
10{
11 showLocal();
12 
13 /* printf("%d", local); ERROR: 'local' is not visible here */
14 return 0;
15}
Output
local = 10

Global Scope — Variable Outside Functions

A variable declared outside every function is global. It is visible to all functions below its declaration, and every function shares the same copy.

Example02
CCode Cell
1#include <stdio.h>
2 
3int global = 100; /* visible to every function */
4 
5void show(void)
6{
7 printf("global = %d\n", global); /* readable here */
8}
9 
10int main()
11{
12 show();
13 global = 200; /* changeable here */
14 show();
15 return 0;
16}
Output
global = 100
global = 200

Local vs Global

Local variableGlobal variable
DeclaredInside a functionOutside all functions
Usable inOnly that functionEvery function
LifetimeUntil the function returnsWhole program
Default valueUninitialised (garbage)Zero
Example03
CCode Cell
1#include <stdio.h>
2 
3int global = 5; /* global */
4 
5int main()
6{
7 int local = 50; /* local */
8 
9 printf("local = %d\n", local);
10 printf("global = %d\n", global);
11 return 0;
12}
Output
local  = 50
global = 5
📝 Key Takeaways
  • A local variable is declared inside a function and is usable only there.
  • A global variable is declared outside every function and is usable everywhere.
  • Local variables are created on entry and destroyed when the function returns.
  • Globals live for the whole program and are shared by all functions.
  • Prefer local variables; use globals only when truly needed.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3