Preprocessor Arithmetic

This tip has been extracted from the main preprocessor arithmetic article.

Preprocessor macros (created with #define directives) define a replacement string. Any macros appearing in C source code are replaced with this string. The string then forms part of a larger C expression and is interpreted and evaluated by the compiler in the usual way.

The preprocessor sees the replacement string as nothing more than characters; it does not parse the string, there is no concept of types or values, and the preprocessor does not evaluate anything resembling an expression.

However, there is one instance where the preprocessor will evaluate expressions, and that is when they appear as the controlling expression of #if or #elif conditional directives, such as in the first line of the following example.

Note that the preprocessor assigns types to integer constants that are different than those assigned by the C compiler. These types typically have different sizes, and hence results obtained by the preprocessor might not be the same as those produced by the compiler for the same expressions appearing in C code.

Take care of the preprocessor expression evaluation, especially if you have macros that are used in both C code and as the controlling expression of a preprocessor conditional directive.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.