是否可以在同一个函数中引用范围外的局部变量? [英] Is it OK to reference an out-of-scope local variable within the same function?

查看:255
本文介绍了是否可以在同一个函数中引用范围外的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我引用了局部变量 b ,即使它超出范围。但是我从同一个函数里面做,所以它可能还在堆栈上,对吧?我运行的程序,它的工作,但我想知道是否保证在所有实现上工作。

In this code, I reference the local variable b even though it is out of scope. But I do it from within the same function so it's probably still on the stack, right? I ran the program and it worked but I'd like to know if it's guaranteed to work on all implementations.

#include <iostream>

void main()
{
    int* a;
    {
        int b = 5;
        a = &b;
    }
    std::cout << *a;
}


推荐答案

不保证工作。 a 一旦退出内部作用域就会悬挂,因此任何取消引用都会导致未定义的行为,并且不会保证任何东西。

No, that's not guaranteed to work. a is dangling once the inner scope is exited, so any dereference of it results in Undefined Behaviour and nothing whatsoever is guaranteed.

这篇关于是否可以在同一个函数中引用范围外的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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