Global vs Static vs Const Variable in C with Example
In C, variables can be declared with various storage classes and qualifiers, such as global
, static
, and const
. Let's go through each one with examples:
1. Global Variable:
A global variable is declared outside of any function and is accessible throughout the entire program.
#include <stdio.h>
// Declaration of a global variable
int global_variable = 42;
int main() {
// Accessing the global variable
printf("The value of global_variable is: %d\n", global_variable);
return 0;
}
In this example, global_variable
is accessible from any part of the program.
2. Static Variable:
A static variable has a scope limited to the block it is declared in, and it retains its value between function calls.
#include <stdio.h>
void example_function() {
// Declaration of a static variable
static int static_variable = 0;
// Accessing and updating the static variable
printf("The value of static_variable is: %d\n", static_variable);
static_variable++;
}
int main() {
// Calling the function multiple times
example_function();
example_function();
example_function();
return 0;
}
In this example, static_variable
retains its value between function calls, and each time example_function
is called, it increments the value.
3. Const Variable:
A const variable is a variable whose value cannot be modified during the program's execution.
#include <stdio.h>
int main() {
// Declaration of a const variable
const int const_variable = 42;
// Accessing the const variable
printf("The value of const_variable is: %d\n", const_variable);
// Uncommenting the next line would result in a compilation error
// const_variable = 50; // Error: assignment of read-only variable 'const_variable'
return 0;
}
In this example, const_variable
is declared as a constant, and any attempt to modify its value results in a compilation error.
Combining Global, Static, and Const:
#include <stdio.h>
// Declaration of a global static const variable
static const int GLOBAL_STATIC_CONST = 42;
int main() {
// Accessing the global static const variable
printf("The value of GLOBAL_STATIC_CONST is: %d\n", GLOBAL_STATIC_CONST);
// Uncommenting the next line would result in a compilation error
// GLOBAL_STATIC_CONST = 50; // Error: assignment of read-only variable 'GLOBAL_STATIC_CONST'
return 0;
}
In this example, GLOBAL_STATIC_CONST
is a global static const variable, combining the characteristics of being global (accessible throughout the program), static (limited scope to the translation unit), and const (value cannot be modified).