Why are global and static variables initialized to their default values in C/C++?

CC++Server Side Programming

Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .bss file and at the time of loading it allocates the memory by getting the constants alloted to the variables.

The following is an example of global and static variables.

Example

 Live Demo

#include <stdio.h>
int a;
static int b;
int main() {
   int x;
   static int y;
   int z = 28;
   printf("The default value of global variable a : %d", a);
   printf("\nThe default value of global static variable b : %d", b);
   printf("\nThe default value of local variable x : %d", x);
   printf("\nThe default value of local static variable y : %d", y);
   printf("\nThe value of local variable z : %d", z);
   return 0;
}

Output

The default value of global variable a : 0
The default value of global static variable b : 0
The default value of local variable x : 0
The default value of local static variable y : 0
The value of local variable z : 28

In the above program, global variables are declared outside the main() function and one of them is static variable. Three local variables are declared and variable z is initialized too.

int a;
static int b;
….
int x;
static int y;
int z = 28;

Their default values are printed.

printf("The default value of global variable a : %d", a);
printf("\nThe default value of global static variable b : %d", b);
printf("\nThe default value of local variable x : %d", x);
printf("\nThe default value of local static variable y : %d", y);
printf("\nThe value of local variable z : %d", z);
raja
Published on 08-Nov-2018 10:28:19
Advertisements