问题描述
假设一个纯粹的非优化编译器,初始化变量和声明后赋值之间的机器代码有什么区别吗?
Assuming a purely non-optimizing compiler, is there any difference in machine code between initializing a variable and assigning it a value after declaration?
初始化方法:
int x = 2;
赋值方法:
int x;
x = 2;
我使用 GCC 输出为这两种不同方法生成的程序集,并且都生成了一条机器指令:
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)
这条指令只是将 x
变量持有的内存设置为 2
的值.GCC 可能正在对此进行优化,因为它可以识别操作的最终结果;但我认为这是解释这两个版本的唯一方法.我的理由是两个版本都做同样的事情:将一部分内存设置为特定值.
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.
如果生成的机器代码相同,为什么经常在术语initialization"和assignment"之间进行区分?
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?
推荐答案
行为必须相同,但生成代码中的任何差异实际上取决于编译器.
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
...
在这些情况下,C 标准不要求生成的代码相同或不相同.它只要求在这两种情况下程序的行为相同.并且相同的行为并不一定意味着相同的机器代码.
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.
这篇关于初始化变量和在声明后立即为其赋值有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!