Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type namespace in C

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?

like image 974
Clynamen Avatar asked Sep 25 '12 08:09

Clynamen


2 Answers

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).
like image 184
Jeegar Patel Avatar answered Sep 18 '22 11:09

Jeegar Patel


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.

like image 38
glglgl Avatar answered Sep 17 '22 11:09

glglgl