In C, static variables can only be initialized using constant literals. For example, following program fails in compilation.
If we change the program to following, then it works without any error.
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.
- Initialization of global and static variables in C
- Difference between Static variables and Register variables in C
- Implicit initialization of variables with 0 or 1 in C
- Initialization of variables sized arrays in C
- Static Variables in C
- How are variables scoped in C - Static or Dynamic?
- What are the default values of static variables in C?
- Internal static variable vs. External static variable with Examples in C
- Initialization of a multidimensional arrays in C/C++
- Initialization of data members
- Static functions in C
- Static data members in C++
- Can static functions be virtual in C++?
- C++ | Static Keyword | Question 4
- C++ | Static Keyword | Question 1