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

函数参数与全局变量同名时,如何在函数内访问全局变量?

Function Parameters vs Global Variables: Same Names & Accessing Shadowed Globals

Great question! Let's break this down step by step:

Can parameters have the same name as global variables?

Absolutely! When you name a function parameter the same as a global variable, the parameter (a local variable scoped to the function) shadows the global one. That means any use of that name inside the function will refer to the parameter by default, not the global variable.

Your code perfectly demonstrates this behavior:

#include<stdio.h>
int x = 12; // Global x
void foo(int x) { // Parameter x shadows the global x
    printf("%d\n",x); // Uses the parameter x (value 3)
}
int main() {
    foo(3);
    printf("%d\n",x); // No local x exists, so uses global x (12)
    return 0;
}

This is exactly why you get the output 3 followed by 12.

How to access the global variable inside foo()?

Since the parameter x is shadowing the global one, you need to explicitly tell the compiler you want the global version. In C, the standard way to do this is using the extern keyword inside the function to redeclare the variable—this tells the compiler to reference the global instance:

void foo(int x) {
    extern int x; // Explicitly point to the global x
    printf("%d\n", x); // Now this prints the global value 12
}

Some compilers might throw a warning about re-declaring x, but this is valid C behavior and will work as intended. If you want to avoid the warning, another approach is to create a pointer to the global variable outside the function, then use that pointer inside foo():

#include<stdio.h>
int x = 12;
int *global_x_ptr = &x; // Pointer to the global x

void foo(int x) {
    printf("%d\n", *global_x_ptr); // Access global x via the pointer
}

int main() {
    foo(3);
    printf("%d\n",x);
    return 0;
}

Quick side note: If this were C++ code instead of pure C, you could use the scope resolution operator ::x directly (like printf("%d\n", ::x);), but that syntax isn't available in standard C.

内容的提问来源于stack exchange,提问作者Aman Sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:12:58