Why are global variables always initialized to '0', but not local variables? [duplicate]

早过忘川 提交于 2019-12-17 03:55:04

问题


Possible Duplicate:
Why are global and static variables initialized to their default values?

See the code,

#include <stdio.h>

int a;
int main(void)
{
    int i;
    printf("%d %d\n", a, i);
}

Output

0 8683508

Here 'a' is initialized with '0', but 'i' is initialized with a 'junk value'. Why?


回答1:


Because that's the way it is, according to the C Standard. The reason for that is efficiency:

  • static variables are initialized at compile-time, since their address is known and fixed. Initializing them to 0 does not incur a runtime cost.

  • automatic variables can have different addresses for different calls and would have to be initialized at runtime each time the function is called, incurring a runtime cost that may not be needed. If you do need that initialization, then request it.




回答2:


global and static variables are stored in the Data Segment (DS) when initialized and block start by symbol (BSS)` when uninitialized.

These variables have a fixed memory location, and memory is allocated at compile time.

Thus global and static variables have '0' as their default values.

Whereas auto variables are stored on the stack, and they do not have a fixed memory location.

Memory is allocated to auto variables at runtime, but not at compile time. Hence auto variables have their default value as garbage.




回答3:


You've chosen simple variables, but consider:

void matrix_manipulation(void)
{
    int matrix1[100][100];
    int matrix2[100][100];
    int matrix3[100][100];

    /* code to read values for matrix1 from a file */
    /* code to read values for matrix2 from a file */
    /* code to multiply matrix1 by matrix2 storing the result in matrix3 */
    /* code to use matrix3 somehow */
}

If the system initialized the arrays to 0, the effort would be wasted; the initialization is overwritten by the rest of the function. C avoids hidden costs whenever possible.




回答4:


Global variables are allocated and initialized before the main function starts, while local variables are generated on the stack as the instance of the program runs.



来源:https://stackoverflow.com/questions/14049777/why-are-global-variables-always-initialized-to-0-but-not-local-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!