Static variable initialization?

后端 未结 7 1128
北海茫月
北海茫月 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:33

    Speaking for java:

    local variables must be initialized before you can access it, because it's a safety gain. The compiler checks for you, if the variable is definitly set.

    static or class variables (with an Object type) are initialized with null, because the compiler can't check if they are initialized at compile time. Instead of letting the program fail if it accesses a non-initialized variable, it will be initialized implicit with null.

    Variables with a native type can't get a null value, so non-local variables are initialized with 0 or false, as a fallback. It's not best solution, sure, but I don't know a better one. ;-)

提交回复
热议问题