type namespace in C

风格不统一 提交于 2020-01-11 09:36:13

问题


I've read in SO about different namespaces in C where the type are defined, e.g. there is a namespace for Structs and Unions and a namespace for typedefs.

Is namespace the exact name for this? How many namespaces exist in C?


回答1:


see 6.2.3

from http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

6.2.3 Name spaces of identifiers

If more than one declaration of a particular identifier is visible at
any point in a translation unit, the syntactic context disambiguates uses
that refer   to different entities.

 Thus, there are separate name spaces for various categories of identifiers,
as follows:
— label names (disambiguated by the syntax of the label declaration and use);

— the tags of structures, unions, and enumerations (disambiguated by 
 following any32) of the keywords struct, union, or enum);

— the members of structures or unions; each structure or union has a 
separate name space for its members (disambiguated by the type of the 
expression used to access themember via the . or -> operator);

— all other identifiers, called ordinary identifiers (declared in ordinary 
  declarators or as enumeration constants).



回答2:


I am not sure if "namespace" is the right word here, but I think I know what you mean.

You can do

union name1 { int i; char c; };
struct name2 { int i; char c; };
enum name3 { A, B, C };
typedef int name4;
int name5;

Here name1, name2 and name3 are in distinct "namespaces" (I'll keep that word for now), as they don't collide with each other.

This implies that using them requires to prefix their use with the respective keyword:

struct name1 var; // valid
name1 var; // invalid

On the other hand, name4 and name5 live in the global "namespace" and collide. So after having typedef int name4;, you cannot define a variable with that name name4.

BTW: The labels as well define their own namespace.



来源:https://stackoverflow.com/questions/12579142/type-namespace-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!