Local vs. Global Scope
Learn about the local and global scopes and get introduced to the structure of an executable file.
We'll cover the following...
Scope
The scope of a variable is the code area in which the variable is visible and usable.
The scope is sometimes called the lifetime of the variable. Variables get destroyed when they go out of scope. We’ll explore the exact mechanism behind the process of destroying local variables very soon!
There are two main scopes:
- Local scope
- Global scope
Global scope
Global scope is the scope of the entire program.
A variable declared inside the global scope:
- Is called a global variable.
- Is visible or accessible in the entire program.
- The lifetime of the variable is the entire runtime of the program.
The following code declares two global variables—global1
and global2
.
Press + to interact
#include <stdio.h>//global1 and global2 are visible everywhere in the programint global1 = 100;float global2 = 3.3f;void otherFunc(){//otherFunc can access the variablesprintf("[otherFunc] %d %f\n", global1, global2);}int main(){//main can access the variablesprintf("[main] %d %f\n", global1, global2);otherFunc();return 0;}
The result of the code complication process is an executable file. Execute the following code widget, which will compile the code, ...