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.
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Understanding "volatile" qualifier in C | Set 1 (Introduction)
- Storage Classes in C
- Static Variables in C
- Scope rules in C
- Understanding "volatile" qualifier in C | Set 2 (Examples)
- Const Qualifier in C
- Memory Layout of C Programs
- How Linkers Resolve Global Symbols Defined at Multiple Places?
- What are the default values of static variables in C?
- Static functions in C
- What is return type of getchar(), fgetc() and getc() ?
- Return values of printf() and scanf() in C/C++
- Understanding "register" keyword in C
- Understanding "extern" keyword in C