C++中变量名能否与函数名同名?同名为何无编译错误?
Short answer: Yes, but only if they’re in different scopes — same-scope collisions will throw a compile error.
Let me break it down:
- If you try to define a global variable
fooand a global functionfoo()in the same top-level scope, the compiler will throw an error. It can’t distinguish which identifier you’re referring to when you use the namefoo. - But if you declare a local variable inside a function that shares the same name as a global function, that’s totally valid. The local variable will "hide" the global function name within that function’s scope. Any reference to the name inside the function will point to the local variable, not the function.
lis既是函数名又是数组名,为何无编译错误? First, let’s restate the code for clarity:
int lis( int arr[], int n ) { int lis[n]; lis[0] = 1; for (int i = 1; i < n; i++ ) { lis[i] = 1; for (int j = 0; j < i; j++ ) if ( arr[i] > arr[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; } // Note: Original code is missing a return statement, but that's unrelated to the naming question }
Here’s why the compiler doesn’t complain, plus the underlying logic:
Scope-based name hiding is the core reason
The functionlislives in the outer (global or namespace) scope, while the arraylisis declared inside the function’s local scope. C++’s scope rules state that local identifiers take precedence over outer ones. Inside the function, every time you writelis, the compiler first checks the local scope, finds the array, and uses that — it never even checks the outer scope for the function name unless you explicitly force it with::lis(the global scope resolution operator), which isn’t used here.Compiler symbol tables handle this cleanly
Compilers store identifiers in a layered symbol table organized by scope. When parsing the function, it adds the local arraylisto the local scope’s entry. Any later references tolisin the function will pull from that local entry, not the outer function entry. There’s no ambiguity here, so no error is triggered.A quick side note on the variable-length array (VLA)
Theint lis[n];line uses a VLA, which isn’t actually part of standard C++ — it’s a GCC extension. But this doesn’t affect the naming collision question; even if it were a fixed-size array likeint lis[10];, the same scope hiding rule would apply.
内容的提问来源于stack exchange,提问作者Charan Das

