In C, static variables can only be initialized using constant literals. For example, following program fails in compilation.
#include<stdio.h> int initializer(void) { return 50; } int main() { static int i = initializer(); printf(" value of i = %d", i); getchar(); return 0; } |
If we change the program to following, then it works without any error.
#include<stdio.h> int main() { static int i = 50; printf(" value of i = %d", i); getchar(); return 0; } |
The reason for this is simple: All objects with static storage duration must be initialized (set to their initial values) before execution of main() starts. So a value which is not known at translation time cannot be used for initialization of static variables.
Thanks to Venki and Prateek for their contribution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Initialization of global and static variables in C
- Difference between Static variables and Register variables in C
- Initialization of variables sized arrays in C
- Implicit initialization of variables with 0 or 1 in C
- Internal static variable vs. External static variable with Examples in C
- How are variables scoped in C - Static or Dynamic?
- What are the default values of static variables in C?
- Static Variables in C
- Initialization of data members
- Initialization of a multidimensional arrays in C/C++
- Static functions in C
- Can static functions be virtual in C++?
- Static data members in C++
- When are static objects destroyed?
- C++ | Static Keyword | Question 1
- C++ | Static Keyword | Question 2
- C++ | Static Keyword | Question 4
- C++ | Static Keyword | Question 5
- C++ | Static Keyword | Question 6
- Count the number of objects using Static member function

