#Define operators in a namespace

If I have a #define statement in the namespace as such:

namespace MyNamespace { #define SOME_VALUE 0xDEADBABE } 

Am I saying correctly that the #define statement is not limited to namespace?

Is the next “right” thing?

 namespace MyNamespace { const unsigned int SOME_VALUE = 0xDEADBABE; } 
+42
c ++ namespaces
Jul 06 '09 at 17:40
source share
5 answers

Right, #define not bound by namespaces. #define is a preprocessor directive - this leads to manipulation of the source file before compilation using the compiler. Namespaces are used during the compilation phase, and the compiler has no idea about #define .

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

+54
Jul 06 '09 at 17:42
source share

I completely agree with the suggestions on using constants and the unlimited scope for #define s.

However, if you do have to use #define preprocessor strings, please attach them correctly for the expected scope,

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

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

+18
Jul 06 '09 at 17:48
source share

The preprocessor works (conceptually, at least, and often actually too) before namespaces and other language-level concepts “hit” - so yes, it is definitely much better to use language constructs such as const values ​​where you can!

+4
Jul 06 '09 at 17:42
source share

Yes. In general, using const values ​​instead of # define'd values ​​has many advantages. Limiting the scope of a variable is one of the advantages. The scope can be limited by namespace or any other valid scope (including at the class level, function level, etc.).

+3
Jul 06 '09 at 17:42
source share

If for some reason you cannot go into the second case, I am sure that you will have to take care of compiling MyNamespace into your own object and linking the objects separately (or maybe just starting the preprocessor on this one namespace). The C ++ preprocessor should accept this #define and essentially replace the line somewhere where SOME_VALUE displayed in the source code. Therefore, if the preprocessor does not know about #define , SOME_VALUE cannot be replaced in another source file.

0
Jul 6 '09 at 17:46
source share



All Articles