A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A local variable is declared inside a function. It is created when the function is entered and destroyed when it exits. It is visible only within its block. A global variable is declared outside any function. It exists for the entire program lifetime. It is visible from its declaration to the end of the file, and to other files via extern. Globals are convenient and dangerous. They create hidden dependencies, prevent reentrancy, complicate testing, and make multithreaded code a minefield. Use them only when you must.
#include <stdio.h>int global_counter = 0;void increment_global(void) {global_counter++;}void increment_local(void) {int local_counter = 0;local_counter++;printf(" local_counter inside: %d\n", local_counter);}int main(void) {printf("Global: %d\n", global_counter);increment_global();increment_global();printf("Global after 2 calls: %d\n", global_counter);printf("\nLocal calls:\n");increment_local();increment_local();increment_local();return 0;}
The global retains its value across calls. It accumulates. The local is created fresh each time. It resets to 0 on every invocation. This is the lifetime difference. The global is also visible to every function in the file, and to other files via extern. Any function can modify it at any time. There is no access control. There is no audit trail. There is only trust.
A function that reads a global depends on every function that writes it. Change one writer and you break readers you did not know existed. In multithreaded code, concurrent reads and writes to a global are a data race unless protected by a mutex. In testing, globals carry state between test cases, causing order-dependent failures. The alternative: pass data as parameters. Return results. Keep state in structs that the caller owns. The function becomes pure: same inputs, same outputs, no hidden dependencies.
Default to local. Pass data explicitly. Return results explicitly. Use static globals for file-private state when you must. Use extern globals almost never. The fewer globals in your code, the fewer hidden dependencies, the fewer concurrency bugs, the easier the testing. Next: interleaving switch cases within other control structures, a legal but dangerous C feature.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.