You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中变量名能否与函数名同名?同名为何无编译错误?

问题1: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 foo and a global function foo() 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 name foo.
  • 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.

问题2:代码中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:

  1. Scope-based name hiding is the core reason
    The function lis lives in the outer (global or namespace) scope, while the array lis is 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 write lis, 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.

  2. 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 array lis to the local scope’s entry. Any later references to lis in the function will pull from that local entry, not the outer function entry. There’s no ambiguity here, so no error is triggered.

  3. A quick side note on the variable-length array (VLA)
    The int 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 like int lis[10];, the same scope hiding rule would apply.

内容的提问来源于stack exchange,提问作者Charan Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:43:09