c++ - 为什么在循环中定义的变量地址在每次迭代中都不变?

标签 c++

for(int i=0; i<10;i++){
    int j = i;
    cout << &j << endl;
}

这将在每次迭代中输出相同的 j 地址。我也注意到 C 中的相同行为。不同的迭代不应该是不同的地址吗?
在 python 中打印了不同的地址,无法在 java 中验证它

for i in range(10):
    j = i
    print(hex(id(j)))

我系统上的 c++ -v 返回这个

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) 

最佳答案

局部变量的地址是编译器的一个实现细节。

当局部变量像这样进入作用域时,编译器可能会重用它之前的相同地址,也可能不会。无论哪种方式,您都不应该依赖它。

实际上,在关闭优化的情况下,编译器每次使用相同的地址很可能更简单。事实上,如果函数 a 多次调用函数 b,函数 b 的局部变量很可能每次都在同一个地方调用函数的时间。

但同样,这是一个实现细节。不能保证不同编译器或具有不同优化设置的同一编译器会出现这种情况。

关于c++ - 为什么在循环中定义的变量地址在每次迭代中都不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47338103/

相关文章:

c++ - 当您声明 "pointer type"形式(函数)参数 "like an const array"时,const 是什么?

c++ - || while 条件下的运算符(operator)未按预期工作

c++ - C++ 标准是否保证字符串文字原封不动地存储在程序二进制文件中?

c++ - QGraphicsWidget 的上下文菜单事件

c++ - 编译错误 : Cannot open precompiled header. pch -- 没有那个文件或目录

类型为 "void(*)(int wall) is incompatible with parameter of type "int 的 C++ 参数”

c++ - 使用 TI-MSP430 的 DSP 的 C/C++ 库或示例代码

c++ - STM32 NVIC ADC 中断未触发

c++ - 尝试从列表中删除元素时出现 "List iterators incompatible"

c++ - Windows 7 64 位 Visual Studio 2013 上的 native cl.exe