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

前端 未结 4 1230
孤街浪徒
孤街浪徒 2020-12-19 21:05

Assuming a purely non-optimizing compiler, is there any difference in machine code between initializing a variable and assigning it a value after declaration?

4条回答
  •  执笔经年
    2020-12-19 21:18

    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.

提交回复
热议问题