Initialization of global and static variables in C

In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known at compile time before the program execution starts. An error will be generated if the constant values are not provided for global and static variables.

Syntax

// Global variable initialization
data_type variable_name = constant_value;

// Static variable initialization
static data_type variable_name = constant_value;

Example 1: Valid Initialization with Constants

This example demonstrates the correct way to initialize global and static variables using constant values −

#include <stdio.h>

int a = 5;           // Global variable initialized with constant
static int b = 10;   // Global static variable initialized with constant

int main() {
    static int c = 15;  // Local static variable initialized with constant
    
    printf("The value of global variable a : %d<br>", a);
    printf("The value of global static variable b : %d<br>", b);
    printf("The value of local static variable c : %d<br>", c);
    return 0;
}
The value of global variable a : 5
The value of global static variable b : 10
The value of local static variable c : 15

Example 2: Invalid Initialization with Non-Constants

This example shows what happens when you try to initialize global or static variables with non-constant values −

#include <stdio.h>

int func() {
    return 25;
}

// This will cause a compilation error
// int global_var = func();  // Error: initializer element is not constant

int main() {
    int x = 10;
    // This will also cause a compilation error
    // static int a = x;  // Error: initializer element is not constant
    // static int b = func();  // Error: initializer element is not constant
    
    printf("This program would not compile with invalid initializations<br>");
    return 0;
}
This program would not compile with invalid initializations

Key Points

  • Global variables must be initialized with compile-time constants (literals, enum values, or constant expressions).
  • Static variables (both global and local) follow the same rule − only constant initialization is allowed.
  • Function calls, variable values, or any runtime expressions cannot be used for initialization.
  • If not explicitly initialized, global and static variables are automatically initialized to zero.

Conclusion

Global and static variables in C must be initialized with constant values known at compile time. Using non-constant expressions will result in compilation errors, ensuring memory layout is determined before program execution.

Updated on: 2026-03-15T10:02:39+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements