Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Global variable: Difference between revisions

From Coderwiki
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'
}

Local 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.