What are the default values of static variables in C?
In C, if an object that has static storage duration is not initialized explicitly, then: — if it has pointer type, it is initialized to a NULL pointer; — if it has an arithmetic type, it is initialized to (positive or unsigned) zero; — if it is an aggregate, every member is initialized (recursively) according to these rules; — if it is a union, the first named member is initialized (recursively) according to these rules. For example, following program prints: Value of g = 0 Value of gs = 0 Value of s = 0
Example no 1
C
#include <stdio.h> int g; // g = 0, global objects have static storage duration static int gs; // gs = 0, global static objects have static // storage duration int main() { static int s; // s = 0, static objects have static // storage duration printf ( "Value of g = %d" , g); printf ( "\nValue of gs = %d" , gs); printf ( "\nValue of s = %d" , s); getchar (); return 0; } |
Output
Value of g = 0 Value of gs = 0 Value of s = 0
Example no 2
C
#include <stdio.h> void print_static_vars( void ) { static int i = 0; static float f = 0.0; static char c = '\0' ; i++; f += 0.1; c++; printf ( "i = %d, f = %f, c = %c\n" , i, f, c); } int main() { print_static_vars(); print_static_vars(); print_static_vars(); return 0; } |
Output
i = 1, f = 0.100000, c = ☺ i = 2, f = 0.200000, c = ☻ i = 3, f = 0.300000, c = ♥
Explanation
- In this program, a function print_static_vars is declared that contains three static variables: i, f, and c. The function increments each of these variables and then prints their values.
- The main function calls the print_static_vars function three times. Since the variables are static, their values persist between calls, and their values are updated each time the function is called.
- As you can see, the default value of a static integer variable is 0, the default value of a static float variable is 0.0, and the default value of a static character variable is \0 (the null character).
Please Login to comment...