简体   繁体   中英

Static and extern variable value assigned to 0 why?

为什么为静态变量分配值0?

Because the standard mandates that this is true.

§6.7.8.10 of the C99 standard says:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules;

— if it is a union, the first named member is initialized (recursively) according to these rules.

Initializing to 0 makes sense - it makes things more predictable. The question should perhaps be "why are stack variables not initialized?"

The answer to this may be performance - initializing stack variables needs to be done whenever entering the function, which may waste time if the initialization isn't actually needed. Static variables are initialized when loading the program, so it doesn't cost much.

Because they are the only variable storage class that can be initialised without incurring a runtime performance penalty.

Automatic storage class variables (the default) are not initialised because they might not be used. Static variables inside a function are not guarenteed to be initialised until the function is called the first time.

Zero is a sensible general default initialiser for several reasons: on a char array it produces an empty string, it starts an array index count, and produces a NULL pointer, etc.

Personally I always explicitly initialise statics, even to zero. This is partly documentary, in other words "I really do want zero, don't change it".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM