Static variable initialization?

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

    So to some extent these are just design decisions on the part of the language designers. But the probable reasons for these decisions in Java are:

    • for static/member variables, if you're going to initialise them to something, then zero is a convenient value because (a) it's generally a suitable value to mean "not set to anything else special", and is the value you would have picked anyway in some cases such as counters; and (b) internally, it's likely that zero can be used for "special" values, notably to represent null in the case of an object reference.
    • for local variables, giving them no default allows for the rule that forces the programmer to set some value before the variable is read, which can actually be useful in allowing the compiler to spot certain errors.

    In the case of local variables, it's also conceivable that a local variable could be declared (which at the bytecode/machine code level essentially means allocating stack space/moving the stack pointer) but then never actually written/read in a particular code path. So not having a default avoids doing unnecessary work of setting a default in those cases.

    I repeat, though, these are design decisions to some extent. They're essentially a tradeoff between what's likely to be convenient for JVM implementations and convenient for programmers.

    N.B. In C/C++, "static" variables mean a different thing to static variables in Java!

    0 讨论(0)
提交回复
热议问题