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 before the execution starts. An error will be generated if the constant values are not provided for global and static variables.

A program that demonstrates the initialization of global and static variables is given as follows.

Example

 Live Demo

#include <stdio.h>
int a = 5;
static int b = 10;
int main() {
   printf("The value of global variable a : %d", a);
   printf("
The value of global static variable b : %d", b);    return 0; }

Output

The output of the above program is as follows.

The value of global variable a : 5
The value of global static variable b : 10

Now, let us understand the above program.

The global variable a has the value 5 and the static variable b has the value 10. So, this program works as required.

If constants are not used to initialize the global and static variables, this will lead to an error. A program that demonstrates this is as follows.

#include <stdio.h>
int func() {
   return 25;
}
int main() {
   static int a = func();
   printf("%d ", a);
}

The above program leads to a error “initializer element is not constant”. So, global and static variables should only be initialized with constants.

Updated on: 26-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements