C语言是否有作用域隐藏?
比如,如果我有一个全局变量:
int x = 3;
我能在函数或主函数中“声明”另一个int x吗?
int x;
void my_function(int x){ // this is another x, not the same one
}
void my_function2(){
int x; //this is also another x
{
int x; // this is yet another x
}
}
int main(){
char x[5]; // another x, with a different type
}
是的,但有些编译器会抱怨或被要求抱怨。对于gcc
,请使用-Wshadow
。
是的,C语言中存在作用域隐藏。
局部作用域中的变量将会隐藏同名的全局作用域中的变量。
x
声明为int
,然后通过声明一个新的类型为char [5]
的x
来隐藏该声明,那么您只会看到后者char x [5]
。 - Adiel Mittmann