Why does the C standard leave use of indeterminate variables undefined?

前端 未结 5 1617
栀梦
栀梦 2020-12-06 06:40

Where are the garbage value stored, and for what purpose?

5条回答
  •  感动是毒
    2020-12-06 07:10

    C chooses to not initialize variables to some automatic value for efficiency reasons. In order to initialize this data, instructions must be added. Here's an example:

    int main(int argc, const char *argv[])
    {
        int x;
        return x;
    }
    

    generates:

    pushl %ebp
    movl  %esp, %ebp
    subl  $16, %esp
    movl  -4(%ebp), %eax
    leave
    ret
    

    While this code:

    int main(int argc, const char *argv[])
    {
       int x=1;
       return x;
    }
    

    generates:

    pushl %ebp
    movl  %esp, %ebp
    subl  $16, %esp
    movl  $1, -4(%ebp)
    movl  -4(%ebp), %eax
    leave
    ret
    

    As you can see, a full extra instruction is used to move 1 into x. This used to matter, and still does on embedded systems.

提交回复
热议问题