Limit scope of #define labels

后端 未结 9 889
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 05:39

What is the correct strategy to limit the scope of #define labels and avoid unwarranted token collision?

In the following configuration:

9条回答
  •  长情又很酷
    2020-12-19 06:17

    What is the correct strategy to limit the scope of #define and avoid unwarrented token collisions.

    Some simple rules:

    1. Keep use of preprocessor tokens down to a minimum.
      Some organizations go so far as down this road and limit preprocessor symbols to #include guards only. I don't go this far, but it is a good idea to keep preprocessor symbols down to a minimum.
      • Use enums rather than named integer constants.
      • Use const static variables rather than named floating point constants.
      • Use inline functions rather than macro functions.
      • Use typedefs rather than #defined type names.
    2. Adopt a naming convention that precludes collisions.
      For example,
      • The names of preprocessor symbols must consist of capital letters and underscores only.
      • No other kinds of symbols can have a name that consists of capital letters and underscores only.

    const UINT ZERO = 0; // Programmer not aware of what's inside Utility.h

    First off, if the programmer isn't away of what's inside Utility.h, why did the programmer use that #include statement? Obviously that UINT came from somewhere ...

    Secondly, the programmer is asking for trouble by naming a variable ZERO. Leave those all cap names for preprocessor symbols. If you follow the rules, you don't have to know what's inside Utility.h. Simply assume that Utility.h follows the rules. Make that variable's name zero.

提交回复
热议问题