← Back to C Course | Chapter 5: Functions | Lesson 6 of 8

C Scope & Lifetime

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

c
#include <stdio.h>
void show() {
	int local = 5;
	printf("%d", local);
}
int main() {
	show();
	return 0;
}

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

c
#include <stdio.h>
int counter = 10;
void show() {
	printf("%d", counter);
}
int main() {
	show();
	return 0;
}

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

c
#include <stdio.h>
int main() {
	if (1) {
		int x = 5;
		printf("%d", x);
	}
	return 0;
}

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

c
#include <stdio.h>
void show() {
	int x = 5;
	printf("%d", x);
}
int main() {
	show();
	return 0;
}

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

c
#include <stdio.h>
int value = 100;
void show() {
	int value = 5;
	printf("%d", value);
}
int main() {
	show();
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.