Sunday 15 January 2012

java - Static variable initialization? -


I want to know that the stabilized variable in C, C ++ and Java is started by zero at default ? And why is it not correct for local variables?

Why are the fixed variables definitely initial and do not have local variables?

See how stable variables are implemented Memory links for them are allocated on time, and the initial value for them is also made available at link time. There is no runtime overhead.

On the other hand, the memory is allocated at run time for local variables. Stack should be increased. You do not know what was before. If you want, you can clear that memory (zero), but it will be a runtime overhead. C ++ philosophy "You do not pay for things you do not use", so by default it does not zero to that memory.

OK, but why is the steady variable started to zero, and there is some other value?

Well, you usually want to do something with that variable, but then how will you know if it has been started? You can make a steady Boolean variable, but then it will have to start with anything trustworthy (preferably incorrect). How about an indicator? You want it to start at NULL, rather than some random waste. How about a structure / record? There are some other data members inside it, it makes sense for them all to start their default values. But for simplicity, if you use the "Start with 0" strategy, then you do not need to check individual members and check their types. You can simply start the whole memory area in 0.

This is not really a technical requirement. The initialization terminology can still be considered sensible if the default value is anything more than 0 but still is deterministic. But then, what should that value be? You can quite easily understand why 0 is used (though in fact it seems a bit arbitrary), but it also seems difficult to explain 1 or 1024 (especially this variable to capture that value Not enough, etc.).

And you can always explicitly initialize the variable.

And you have a passage of C ++ standard 8.5.6, which says, "Every object of static storage period will be zero-initial on program startup".

For more information, please refer to these other questions:

< / Html>

No comments:

Post a Comment