Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define statements within a namespace

Tags:

c++

namespaces

If I have a #define statement within a namespace as such:

namespace MyNamespace
{
  #define SOME_VALUE 0xDEADBABE
}

Am I correct in saying that the #define statement is not restricted to the namespace?

Is the following the "correct" thing to do?

namespace MyNamespace
{
  const unsigned int SOME_VALUE = 0xDEADBABE;
}
like image 766
Soo Wei Tan Avatar asked Jul 06 '09 17:07

Soo Wei Tan


3 Answers

Correct,#define's aren't bound by namespaces. #define is a preprocessor directive - it results in manipulation of the source file prior to being compiled via the compiler. Namespaces are used during the compilation step and the compiler has no insight into the #define's.

You should try to avoid the preprocessor as much as possible. For constant values like this, prefer const over #define's.

like image 151
Michael Avatar answered Oct 20 '22 20:10

Michael


I completely agree with the suggestions on the use of constants and the scope being unlimited for #defines.

However, if you do have to use preprocessor #define lines, please cover them up correctly for the expected scope,

namespace MyNamespace
{
  #define SOME_VALUE 0xDEADBABE
  // your code
  #undef SOME_VALUE
}

Why #defines?
I know one case where an embedded platform did not support constants in the code.
There was no way to initialize them...
It always helps to be more readable.

like image 27
nik Avatar answered Oct 20 '22 22:10

nik


The preprocessor operates (conceptually at least, and often actually too) before namespaces and other language-level concepts "kick in" -- so yes, it's definitely much better to use language-level constructs such as const values wherever you can!

like image 5
Alex Martelli Avatar answered Oct 20 '22 22:10

Alex Martelli