且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在循环内定义的变量的地址在每次迭代中都保持不变?

更新时间:2022-06-24 03:39:20

局部变量的地址是编译器的实现细节.

The address of a local variable is an implementation detail of the compiler.

当本地变量进入这样的范围时,编译器可能会重用以前使用的相同地址,也可能不会.您不应以任何方式依赖它.

When a local comes into scope like this, the compiler might reuse the same address it had before, or it might not. You shouldn't depend on it either way.

实际上,在关闭优化的情况下,编译器每次使用相同的地址很可能会更简单.实际上,如果函数 a 多次调用函数 b ,则函数 b 的局部变量很可能位于同一位置函数被调用的时间.

In practice, with optimizations turned off, it's most likely simpler for the compiler to use the same address each time. In fact, if function a were to call function b multiple times, the local variables of function b will most likely be in the same place each time the function is called.

但是,这又是一个实现细节.无法保证在不同的编译器上,或者在具有不同优化设置的同一编译器上都是这种情况.

But again, this is an implementation detail. There's no guarantee this will be the case across different compilers, or on the same compiler with different optimization settings.