C/C++ Why do you use namespace in C++?

  • Thread starter Thread starter Avichal
  • Start date Start date
AI Thread Summary
Namespaces are essential in programming to prevent naming collisions between libraries, a feature absent in C but present in languages like C++, C#, Java, and Python. In C, including two libraries with the same function name leads to conflicts, necessitating either long function names or risking errors. Namespaces, such as the 'std' namespace in C++, allow developers to group related functions and avoid these conflicts. While it's possible to use unique function names instead, namespaces significantly expand the pool of collision-free names and enhance code organization. Although not strictly necessary, namespaces provide considerable convenience, especially in larger, more complex programs. The absence of namespaces in C can be attributed to its development in the 1970s when programming was less complex and did not require such features.
Avichal
Messages
294
Reaction score
0
As far as I could understand namespaces are used to avoid collision between libraries? C doesn't have this feature, then why was this feature necessary in c++? And do other languages have this feature too?
 
Technology news on Phys.org
C++ and C# have namespaces, java has packages, python has modules, perl has modules. C doesn't have anything like this. You either emulate the concept with big long names or suffer the consequences.
 
I don't think I understand namespaces that well. So here is my understanding: - In C two libraries cannot have same names of functions as if we include both we'll have a conflict.
So to avoid this conflict we have namespaces. So when we use std namespace we only refer to libraries that are under std.
Am I right?

But does namespace really help? We can always have different names of functions right?
 
Avichal said:
But does namespace really help? We can always have different names of functions right?

What happens then if you end up using two libraries that end up having the same function name?

The set of possible collision-free names is much larger with namespaces than it is without. Namespaces are a nice feature. Strictly speaking, they're not absolutely necessary, but they are a huge convenience.
 
jhae2.718 said:
What happens then if you end up using two libraries that end up having the same function name?

The set of possible collision-free names is much larger with namespaces than it is without. Namespaces are a nice feature. Strictly speaking, they're not absolutely necessary, but they are a huge convenience.

Yeah okay I guess they might be useful. Since I have not made any programs that require use of many libraries I might not realize it. Anyways, why didn't C include ths feature then?
 
C is relatively ancient as a computer language. When it was invented in the 1970s, people didn't write programs that are nearly as large and complex as they can be nowadays.
 
Got it, thank you guys!
 
Back
Top