A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Scope determines where a name is visible. C has four scope categories: block scope (inside braces), file scope (outside any function, visible to the end of the file), function scope (only labels, visible throughout the function), and function prototype scope (inside parameter declarations). The one you deal with constantly is block scope. A variable declared inside a block exists from its declaration to the closing brace. Outside that block, the name does not exist. The compiler rejects any reference to it.
#include <stdio.h>int global_var = 100;void demo(void) {int local_var = 200;{int inner_var = 300;printf("Inner block: global=%d, local=%d, inner=%d\n",global_var, local_var, inner_var);}printf("Outer block: global=%d, local=%d\n", global_var, local_var);}int main(void) {demo();printf("Main: global=%d\n", global_var);return 0;}
#include <stdio.h>int x = 10;int main(void) {printf("Global x: %d\n", x);int x = 20;printf("Local x: %d\n", x);{int x = 30;printf("Inner x: %d\n", x);}printf("Local x again: %d\n", x);return 0;}
Three variables named x. The innermost declaration wins within its block. The local x shadows the global x. The inner x shadows the local x. When the inner block ends, the inner x is destroyed and the local x is visible again. The -Wshadow flag warns about this. Shadowing is legal but confusing. Avoid it in production code. Give variables distinct names.
Scope is where a name is visible. Lifetime is when the storage exists. A local variable has block scope and automatic lifetime: it is created when the block is entered and destroyed when the block is exited. A static local variable has block scope but static lifetime: the name is only visible inside the block, but the storage persists for the entire program. A global variable has file scope and static lifetime. These are orthogonal concepts. Confusing them leads to bugs with static locals and returned pointers.
Scope is the visibility rule. Lifetime is the existence rule. They are related but distinct. Understand both and you understand why returning a pointer to a local variable crashes, why static locals retain their value, and why globals are visible everywhere. Next: the main function's return value, and what it communicates to the operating system.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.