简体   繁体   English

预编译器会评估移位和算术运算吗?

[英]Will bitshift and arithmetic operations be evaluated by the precompiler?

If I define the following in a C++98 program: 如果我在C ++ 98程序中定义以下内容:

#define BITS_PER_FOO 2
#define BITS_PER_BAR 3
#define FOOBARS (1<<(BITS_PER_FOO*BITS_PER_BAR))

then will FOOBARS get evaluated as 64 by the precompiler? 那么预编译器会将FOOBARS评估为64吗? Or will a multiplication and bit-shift operation take place at each location that I use FOOBARS in the code? 还是在我在代码中使用FOOBARS每个位置上进行乘法和移位操作?

No, since it's not the preprocessor's business. 不,因为这不是预处理器的业务。 It does the usual replace thing, not constant folding. 它执行通常的替换操作,而不是不断折叠。

However, any reasonable compiler will do constant folding, so you should not expect this to correspond to instructions being executed at runtime. 但是,任何合理的编译器都会进行常量折叠,因此您不应期望它与运行时正在执行的指令相对应。

The precompiler just does text substitution - it's essentially copy & paste on steroids. 预编译器只是进行文本替换-本质上是在类固醇上复制并粘贴。 This means that the expression you wrote for FOOBAR will be expanded in full at each replacement location. 这意味着您为FOOBAR编写的FOOBAR将在每个替换位置完全展开。

Now, any decent compiler will evaluate that whole subexpression at compile time anyway. 现在,无论如何,任何合适的编译器都会在编译时评估整个子表达式。 However, you can save it some work (and have some extra advantages, like having a clear type of your expression, clearer diagnostic, less surprises deriving from substitutions in the wrong places, and having an actual lvalue for your constants instead of expressions) by defining these values as actual constants, like: 但是,您可以通过以下方式为它节省一些工作(并具有一些额外的优势,例如,具有清晰的表达式类型,更清晰的诊断,在错误的位置进行替换而产生的较少惊喜以及为常量而不是表达式提供实际的左值)将这些值定义为实际常量,例如:

const int bits_per_foo = 2;
const int bits_per_bar = 3;
const int foobars = 1<<(bits_per_foo*bits_per_bar);

A multiplication and bit-shift operation will take place at each location that you use FOOBARS . 您使用FOOBARS每个位置都会进行乘法和移位操作。

See: #define Directive (C/C++) 请参阅: #define指令(C / C ++)

#define forms a macro, meaning the identifier is replaced with everything in the token-string. #define构成一个宏,这意味着标识符将被令牌字符串中的所有内容替换。 In your case, the preprocessor replaces instances of FOOBARS with the expression (1<<(BITS_PER_FOO*BITS_PER_BAR)) 在您的情况下,预处理器将FOOBARS实例替换为表达式(1<<(BITS_PER_FOO*BITS_PER_BAR))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM