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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- What are the default values of static variables in C?
- How are variables scoped in C - Static or Dynamic?
- Internal static variable vs. External static variable with Examples in C
- Initialization of data members
- Initialization of a multidimensional arrays in C/C++
- Static functions in C
- Static data members in C++
- C++ | Static Keyword | Question 2
- C++ | Static Keyword | Question 3
- C++ | Static Keyword | Question 4
- C++ | Static Keyword | Question 5
- C++ | Static Keyword | Question 6
- C++ | Static Keyword | Question 1
- When are static objects destroyed?
- Can static functions be virtual in C++?