Home > OS >  Why we need 'namespace scope' concept? - in C
Why we need 'namespace scope' concept? - in C

Time:07-07

I learned that in namespace "name decoration(mangling)" takes place so that it can be differentiated from other same identifiers which is in different namespace. Wiki: Name mangling

If then, Why "namespace scope" exists? I thought just 'name decoration' can solve all problem about name conflicting. Because in C, the reason for name conflicting is eventually that "different entities have same identifier". Name decoration can make names(identifiers) different from each other internally, so I think name decoration is what all we need.

Then, why C use 'namespace scope' concept? Just for to use unqualified name in namespace scope? I want to know if there is any reason.

CodePudding user response:

Namespaces scope is very useful in programming for the following reasons:

  1. Avoids name collisions between functions/classes, eg., Suppose you have two functions of same name but in different namespace scope (foo::func() and bar::func())
  2. Can be used for managing similar functions inside it, eg., sin(), cos() and sqrt() function could be under namespace Math.
  3. Avoids confusion between classes for an example suppose there's two classes named lexer, but in different namespace scope like json::lexer and xml::lexer. Now, it gives clear understanding to the programmer to choose between them according to their language i.e, xml or json.

An everyday example of namespace could be std, stands for standard, it contains every single functions and classes defined in the standard library, it also includes STL classes like std::vector, std::map and std::string.

NOTE: There's no concept of namespace scope in C.

CodePudding user response:

Namespace scope is a concept in the programming language that the developer sees, allowing them to organise their code effectively and understand it better. Name mangling is something the compiler does under the hood in order to implement namespaces (including namespace scope) in a way the linker can understand. In normal circumstances the developer doesn't need to think about name mangling, although its useful to know how it works.

  •  Tags:  
  • c
  • Related