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:
- Avoids name collisions between functions/classes, eg., Suppose you have two functions of same name but in different namespace scope (
foo::func()
andbar::func()
) - Can be used for managing similar functions inside it, eg.,
sin()
,cos()
andsqrt()
function could be under namespaceMath
. - Avoids confusion between classes for an example suppose there's two classes named
lexer
, but in different namespace scope likejson::lexer
andxml::lexer
. Now, it gives clear understanding to the programmer to choose between them according to their language i.e,xml
orjson
.
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.