为什么局部变量的地址对于不同的执行是相同的? [英] Why is the address of a local variable identical for different executions?

查看:174
本文介绍了为什么局部变量的地址对于不同的执行是相同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int fun(int x);

int main()
{
    fun(10);
    fun(11);   
    return 0;
}

int fun(int x)
{
    int loc;//local variable
    cout<<&loc;
    return 0;
}

输出为

0xbfb8e610 
0xbfb8e610

变量,它在第一次执行函数 f(10)之后超出范围,然后再次为下一次执行 fun )。因此,根据我的理解, loc 变量的地址必须不同。为什么地址& loc 对于执行都相同?

Here loc is a local variable, which goes out of scope after the 1st execution of the function f(10), then get allocated again for the next execution of fun(11). So the address of loc variable has to be different as per my understanding. Then why is the address &loc same for both the execution?

推荐答案

fun 的每次调用都需要自己的地方来存储变量。但是一旦函数返回,变量就不再存在。没有理由地址不能重复使用。

Each invocation of fun needs its own place to store the variable. But as soon as the function returns, the variable no longer exists. There's no reason the address can't be re-used. It doesn't have to be, but there's no reason it can't be.

在一个典型的实现中,堆栈空间用于保存返回所需的信息当函数被调用时,它们的局部变量。当函数返回时,局部变量从堆栈中移除,并且返回信息弹出,使堆栈返回函数被调用时的位置。由于两个函数调用是相同的,它们在堆栈中都是相同的,这使得局部变量具有相同的地址。这是一个有经验的程序员所期望的,但不依赖。

In a typical implementation, stack space is used to hold the information needed to return from a function and their local variables when a function is invoked. When the function returns, the local variables are removed from the stack and the return information popped off it, leaving the stack back where it was when the function was called. Since the two function invocations are the same, they wind up with the stack the same in both cases, making the local variable have the same address. This is what an experienced programmer would would expect, but not rely on.

这篇关于为什么局部变量的地址对于不同的执行是相同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆