#define statements within a namespace

前端 未结 5 1557
旧巷少年郎
旧巷少年郎 2021-02-01 12:34

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

namespace MyNamespace
{
  #define SOME_VALUE 0xDEADBABE
}

Am I correct in saying that

相关标签:
5条回答
  • 2021-02-01 12:57

    Yes. In general, using const values instead of #define'd values has many advantages. Restricting the scope of the variable is one of the advantages. The scope can be restricted to a namespace, or to any another valid scope this way (including at the class level, function level, etc).

    0 讨论(0)
  • 2021-02-01 12:58

    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!

    0 讨论(0)
  • 2021-02-01 13:00

    If, for some reason, you couldn't change to the second case, I'm pretty sure you would have to take care to compile MyNamespace into its own object and link the objects separately (or possibly just run the preprocessor on that single namespace by itself). The C++ preprocessor should take that #define statement and essentially do a string replace anywhere that SOME_VALUE is seen in the source code. Hence if the preprocessor is not aware of the #define, SOME_VALUE cannot be replaced in another source file.

    0 讨论(0)
  • 2021-02-01 13:14

    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.

    0 讨论(0)
  • 2021-02-01 13:19

    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.

    0 讨论(0)
提交回复
热议问题