为什么在函数中已存在的宏中声明同名变量时没有收到警告?
Why don't I get a warning when I declare a variable with same name in a macro that already exists in a function?
玩宏并思考以下场景。在调用该宏的函数中已经存在的宏中声明变量,为什么编译器不抱怨。当我在代码中声明一个变量时,它会给我一个警告:
Redefinition of 'temp'
我认为这是预期的行为,必须记录在标准 (ANSI C) 中,但找不到位置。
例如这段代码:
#define TEST() { \
int temp = 10; \
}
int main() {
int temp = 999;
printf("\ntemp: %d", temp);
TEST();
printf("\ntemp: %d", temp);
}
宏扩展为一个块。块内部是一个单独的范围,您可以在其中声明与外部同名的变量。它们会影响外部变量。这样做通常不是一个好主意。
根据您的代码和上面的宏,C preprocessor 生成以下内容:
int main() {
int temp = 999;
printf("\ntemp: %d", temp);
{
int temp = 10;
}
printf("\ntemp: %d", temp);
}
这是 C 编译器接收到的代码。
里面的{ .. }
叫做nested scope. In your case this nested inner scope contains a variable temp
, of which there is already one in the surrounding outer scope (variable shadowing)。这会触发您看到的警告。
注意:在您的特定示例中,temp
变量在嵌套范围内声明,从未使用过,范围关闭从而删除该变量。它本质上是一个 NOP.
玩宏并思考以下场景。在调用该宏的函数中已经存在的宏中声明变量,为什么编译器不抱怨。当我在代码中声明一个变量时,它会给我一个警告:
Redefinition of 'temp'
我认为这是预期的行为,必须记录在标准 (ANSI C) 中,但找不到位置。
例如这段代码:
#define TEST() { \
int temp = 10; \
}
int main() {
int temp = 999;
printf("\ntemp: %d", temp);
TEST();
printf("\ntemp: %d", temp);
}
宏扩展为一个块。块内部是一个单独的范围,您可以在其中声明与外部同名的变量。它们会影响外部变量。这样做通常不是一个好主意。
根据您的代码和上面的宏,C preprocessor 生成以下内容:
int main() {
int temp = 999;
printf("\ntemp: %d", temp);
{
int temp = 10;
}
printf("\ntemp: %d", temp);
}
这是 C 编译器接收到的代码。
里面的{ .. }
叫做nested scope. In your case this nested inner scope contains a variable temp
, of which there is already one in the surrounding outer scope (variable shadowing)。这会触发您看到的警告。
注意:在您的特定示例中,temp
变量在嵌套范围内声明,从未使用过,范围关闭从而删除该变量。它本质上是一个 NOP.