为什么在循环内定义的变量的地址在每次迭代中都保持不变?
for(int i=0; i<10;i++){
int j = i;
cout << &j << endl;
}
这将在每次迭代中输出相同的 j
地址.我还注意到C中的行为相同.对于不同的迭代,它是否应该是一个不同的地址?
在python中打印了不同的地址,无法在java中验证它
This will output the same address of j
in each iteration. I also noticed the same behavior in C. Shouldn't it be a different address for different iteration ?
In python different address is printed, couldn't verify it in java
for i in range(10):
j = i
print(hex(id(j)))
我系统上的c ++ -v返回此
c++ -v on my system returns this
Using built-in specs.
COLLECT_GCC=c++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.2.0-8ubuntu3' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.2.0 (Ubuntu 7.2.0-8ubuntu3)
局部变量的地址是编译器的实现细节.
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.