Jump to content
  • Advertisement
Sign in to follow this  
Toadhead

[C++] Use of unnamed namespaces

This topic is 3494 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a question about the unnamed namespaces in C++. If I understand it correctly, you can use a unnamed namespace to avoid conflicts with global variables with the same name. But my question is, why using an unnamed namespace instead of just a block using { and } ? If you put code between {}'s you'll make the code local right, than it wont conflict with the global variables with the same name either. Can someone comment on this? Kind regards, Rob

Share this post


Link to post
Share on other sites
Advertisement
Because at namespace scope you can't just use {} to create a new block. It won't compile.

Share this post


Link to post
Share on other sites
The purpose of anonymous namespaces isn't to avoid conflicts with global variables. The purpose of anonymous namespaces is to make "file local" variables, types and functions. As a general rule I always put "helper" functions in an anonymous namespace.

As for why you would use an anonymous namespace over a block, they aren't interchangeable. A namespace can only be nested inside other namespaces (including the global namespace), it cannot be inside a function or type. An anonymous block can only be inside functions.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!