0de*_*al0 2 c namespaces name-lookup
命名空间中是否有查找顺序,即标记命名空间和普通名称空间?请考虑以下代码:
#include <stdio.h>
int main (void){
typedef struct{ //This belongs to ordinary name space
int min;
} st;
st myst;
myst.min=6;
struct myst{ // This belongs to tag name space
int min;
};
myst.min=7;
printf("%d\n%d\n",myst.min,myst.min);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
7
7
我想,编译器会先查找要在标记命名空间中打印的变量.我不知道是否在普通命名空间中对同一个标识符进行了查找,如果完成,我也无能为力,为什么它不打印它.
C中没有命名空间查找顺序.任何特定标识符都只考虑一个命名空间; 它取决于查找的标识符类型.结构标签是一种,具有自己的命名空间; 变量名称属于"普通标识符"的更广泛类别,它具有单独的名称空间.还有其他名称空间,但编译器总是可以从上下文告诉哪一个与任何给定的标识符相关.
因此,在你的程序中,两个用途都myst.min引用声明为的st myst;变量,并且"tag"命名空间中没有任何第二个变量(正如你似乎认为的那样).
你可以通过评论main上面的所有内容来自己看到这个myst.min = 7:
#include <stdio.h>
int main (void){
#if 0
typedef struct{ //This belongs to ordinary name space
int min;
} st;
st myst;
myst.min=6;
#endif
struct myst{ // This belongs to tag name space
int min;
};
myst.min=7;
printf("%d\n%d\n",myst.min,myst.min);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试编译它会产生一个硬错误:
test.c: In function ‘main’:
test.c:14:3: error: ‘myst’ undeclared (first use in this function)
Run Code Online (Sandbox Code Playgroud)
什么struct myst声明确实是声明另一个类型,然后你就可以用它来声明变量.但除非你真的这样做,否则它不会用于任何事情.例如
#include <stdio.h>
typedef struct { int min; } st;
struct myst { int min };
int main(void)
{
// uses the typedef name 'st', in the ordinary namespace,
// to declare the variable 'myst', also in the ordinary namespace
st myst = { 6 };
// uses the struct name 'myst', in the tag namespace,
// to declare the variable 'myst2', in the ordinary namespace
struct myst myst2 = { 7 };
printf("%d %d\n", myst.min, myst2.min);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将打印6 7.该程序还说明myst了变量和myst结构标记如何确实位于两个不同的名称空间中,并且可以独立引用.
(感谢John Bollinger的新第一段.-ed)