Related Articles

Related Articles

Initialization of static variables in C
  • Difficulty Level : Easy
  • Last Updated : 31 Jul, 2018

In C, static variables can only be initialized using constant literals. For example, following program fails in compilation.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int initializer(void)
{
    return 50;
}
  
int main()
{
    static int i = initializer();
    printf(" value of i = %d", i);
    getchar();
    return 0;
}

chevron_right


If we change the program to following, then it works without any error.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
    static int i = 50;
    printf(" value of i = %d", i);
    getchar();
    return 0;
}

chevron_right


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 C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :