gpt4 book ai didi

C - 防止在 block 作用域中使用相同的变量名

转载 作者:太空狗 更新时间:2023-10-29 16:06:22 28 4
gpt4 key购买 nike

我继承了一些代码,我将对其进行重构,这些代码在不同范围内广泛使用具有相同名称的多个变量,即:

int test = 456;
int main(void) {
int test = 0;
//...

for (i=0; i<MAX_VAL; i++) {
int test = 123;
//...
}
return 0;
}

我知道,如果相同的变量名称仅在两个相关级别的范围内使用, I can access the globally accessible one by declaring extern int test within the deeper/lower levels of scope 。虽然有两个以上的级别,但我不确定正在访问哪个 test 变量:全局范围变量或更高一级范围的变量。

我决定重新编写代码以使用不同的变量名,并且在这样做的过程中发现了很多过去难以追踪的错误。当使用这种行为时,有没有办法触发警告?我必须通过 GCC 在 Linux 中编译代码,在 Windows 中通过 Visual Studio 2010 编译代码。如果无法采用可移植的方法,那么这些编译器中的每一个是否有办法警告不同范围内具有相同名称的多个变量?这将使我能够构建代码并获得使用此类行为的所有位置的列表。

谢谢。

最佳答案

gcc 和 clang 都支持 -Wshadow 标志,该标志警告变量相互遮蔽:

-Wshadow

Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum.

来自 Visual Studio 2015 you get a warning by default:

Shadowed variables

A variable declaration "shadows" another if the enclosing scope already contains a variable with the same name. For example:

void f(int x)
{
int y;
{
char x; //C4457
char y; //C4456
}
}

The inner declaration of x shadows the parameter of function f, so the compiler will emit:

warning C4457: declaration of 'x' hides function parameter

The inner declaration of y shadows the declaration of y in the function scope, so the compiler will emit:

warning C4456: declaration of 'y' hides previous local declaration

Note that, as before, a variable declaration with the same name as a function parameter but not enclosed in an inner scope triggers an error instead:

 void f(int x)
{
char x; //C2082
}

The compiler emits:

error C2082: redefinition of formal parameter 'x'

对于旧版本的 Visual Studio,您可以启用 Code Analysis(请参阅 How do I enable the 6000 series warnings (code analysis warnings) in MSVC++?)并查看警告 C6244C6246

关于C - 防止在 block 作用域中使用相同的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32254127/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com