Static variable initialization?

后端 未结 7 1125
北海茫月
北海茫月 2020-11-30 08:05

I want to know why exactly static variables in C, C++ and Java are initialized by zero by default? And why this is not true for local variables?

7条回答
  •  悲&欢浪女
    2020-11-30 08:42

    This has to do with the concept of "only pay for what you use" in C/C++.

    For static variables, an initialization can be made without generating code. The object file contains the initial values for the variables in the data segment and when the OS loads the executable it loads and maps this data segment before the program starts executing.

    For local variables there's no way to initialize them without code because they are not initialized once, they should be initialized every time you enter their scope; also they are allocated in the stack, and when the allocation occurs the initial value in the stack in the general case is simply what was there before (except those rare moments you grow the stack more than it has grown before).

    So to implicitly initialize a local variable the compiler would need to generate code without the programmer explicitly commanding it to do so, which is quite against that "philosophy".

    About Java, as far as I know, variables are always initialized when the program enters their scope, no matter if they are static or not. The only significant difference between them is that the scope of static variables is the entire program. Given that, the behavior is consistent among all of them.

提交回复
热议问题