Is there a difference between initializing a variable and assigning it a value immediately after declaration?

assembly, c, c99, initialization, variable-assignment

Solution

The behavior must be identical, but any differences in the generated code really depend on the compiler.

For example, the compiler could generate this for the initialized variable:

somefunction:
pushl    %ebp
movl     %esp, %ebp
pushl    $2 ; allocate space for x and store 2 in it
...

and this for the uninitialized, but later assigned variable:

somefunction:
pushl   %ebp
movl    %esp, %ebp
subl    $4, %esp ; allocate space for x
...
movl    $2, -4(%ebp) ; assign 2 to x
...

The C standard does not mandate the generated code to be identical or non-identical in these cases. It only mandates identical behavior of the program in these two cases. And that identical behavior does not necessarily imply identical machine code.

Problem

Assuming a purely non-optimizing compiler, is there any difference in machine code between initializing a variable and assigning it a value after declaration? Initialization method: ``` int x = 2; ``` Assignment method: ``` int x; x = 2; ``` I used GCC to output the assembly generated for these two different methods and both resulted in a single machine instruction: ``` movl $2, 12(%esp) ``` This instruction just sets the memory held by the `x` variable to the value of `2`. GCC may be optimizing this because it can recognize the end result of the operations; but I think this is the only way to interpret the two versions. My reasoning is that both version do the same thing: set a part of memory to a specific value. Why is it then that a distinction is often made between the terms "initialization" and "assignment" if the resulting machine code is the same? Is the term "initialization" used purely to differentiate variables which have a specific value assigned over those (non-initialized) variables which have whatever garbage value was left in memory?

Original source