Global variable: Difference between revisions
From Coderwiki
More actions
info, C example, comparison to local variables |
(No difference)
|
Latest revision as of 10:36, 12 August 2025
A global variable is a variable which is valid throughout the lifetime of the program's execution.
By definition, it does not have a scope.
Example of a global variable in C
edit edit source#include <stdio.h>
int number = 6;
void printNumber() { // no parameters...
printf("%d", number); // ... but we can still access 'number'
}
int main() {
number = 12; // assign a new value to global variable 'number'
printNumber(); // prints '12'
}
Comparison to local variables
edit edit sourceLocal variables are only valid inside a specific scope.
Usually, this scope is a code block, such as an if statement or subroutine (function or procedure).
Global variables on the other hand are not bound to a specific scope or code block, but can instead be accessed anywhere in the program.