当前位置:C++技术网 > 资讯 > C++局部变量隐藏全局变量的规则

C++局部变量隐藏全局变量的规则

更新时间:2016-03-01 22:18:12浏览次数:1+次

在c++中,如果全局变量和局部变量的名称相同,则在执行的时候,全局变量将被隐藏;看下面代码:
#include<iostream>

using namespace std;

int temp = 12;
void test(void );
int main(void )
{
                 int temp = 13;
                cout << "in main: " << temp <<"    address: " << endl;
                test();
                cout << "in main: " << temp << "    address":  << &temp << endl;
                 return 0;

}
void test(void )
{
                 int temp = 14;
                cout << "in func: " << temp << "       address":  << &temp << endl;
                {
                                 int temp = 15;
                                cout << "in func block: " << temp << "            address: " << &temp << endl;
                }
                cout << "in func: " << temp << "       address: " << &temp << endl;

}

从结果上面看出,全局变量和局部变量同名的情况下,局部变量会显示,而全局变量会被局部变量隐藏,在局部变量作用完了之后,全局变量才显现出来