Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

like image 451
subanki Avatar asked Jul 14 '10 16:07

subanki


1 Answers

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.

like image 138
Rannick Avatar answered Nov 15 '22 19:11

Rannick