我如何在C ++的另一个作用域中使用局部变量? [英] How can I use local variable in another scope in C++?

查看:119
本文介绍了我如何在C ++的另一个作用域中使用局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在另一个作用域中访问main函数的局部变量。

我的目标是在 cout 中打印20。

如何做到这一点?

在C ++中怎么可能?

I want to access a local variable of main function in another scope.
My goal is to print 20 in cout.
How can I do this?
How is it possible in C++?

int var = 10;

int main(int argc, char *argv[])
{
    int var = 20; // this var
    {
        int var = 40;
        cout << ::var; // I want to print `var` variable in main scope.
                       // But this command print global variable.
    }

    return 0;
}


推荐答案

没有办法完成那。该语言没有提供区分 main 中的第一个 var 与第二个之间的区别的方法。 var

There is no way to accomplish that. The language does not provide a way to differentiate between the first var in main from the second var.

如果您曾经编写过产品代码,请不要使用这些变量。它会导致错误的代码。您会对给定代码行中的变量在范围内感到困惑。

If you ever write production code, please refrain from using such variables. It will lead to buggy code. You will be confused about which variable is in scope in a given line of code.

这篇关于我如何在C ++的另一个作用域中使用局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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