Why do you use namespace in C++?

  • Context: C/C++ 
  • Thread starter Thread starter Avichal
  • Start date Start date
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 2K views
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?
 
Physics news on Phys.org
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?
 
Got it, thank you guys!