Why is it compulsory and necessary to initialize static variables during compile time only?

Recommended Answers

All 4 Replies

It's not compulsory.

@deceptikon I know if you dont initialize it by default it gets initialized to 0 my question was why does it gets inialized during COMPILE time only?

my question was why does it gets inialized during COMPILE time only?

The zero initialization is historically due to where static variables were stored in the executable image. They were typically placed in the BSS segment of the image, which typically included zero initialization of memory blocks. The C standard then blessed the semantics of zero initialization for statically linked objects, and we're where we are now.

A long long long time ago, when I first got into programming, FORTRAN, COBOL, and then C. The compilers did not give the guarantee to initialize a variable (static or otherwise) to 0. They were given arbitrary addresses available in the program stack, and if another number was already in that address...well, yours wasnt 0. For the most part, unless it was a counter variable (or another which was expected to be 0), it wasnt a huge deal, because youd initialize them with a function to a specific value anyway.Since the early 90s...dont quote me on that, compilers initialize variables to 0 from the start, unless you are manually assigning memory address locations for them. It is still considered proper form in ANSI C/C99 to initialize to zero....mostly because thats how it used to be done and ensures your functions perform as intended.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.