As the questions says, is the C preprocessor able to do it?
E.g.:
#define PI 3.1416 #define OP PI/100 #define OP2 PI%100 Is there any way OP and/or OP2 get calculated in the preprocessing phase?
The preprocessor does not do math. The results of preprocessor arithmetic can be used, for conditional preprocessor directives, inside the current preprocessor phase, but substitutions resulting from #defined expressions that are passed to the compiler are text (the replacement list).
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs.
There are 4 Main Types of Preprocessor Directives:Macros. File Inclusion. Conditional Compilation. Other directives.
One unique operator used in preprocessing and nowhere else is the defined operator. It returns 1 if the macro name, optionally enclosed in parentheses, is currently defined; 0 if not. The #endif command ends a block started by #if , #ifdef , or #ifndef .
Integer arithmetic? Run the following program to find out:
#include "stdio.h" int main() { #if 1 + 1 == 2 printf("1+1==2\n"); #endif #if 1 + 1 == 3 printf("1+1==3\n"); #endif } Answer is "yes", there is a way to make the preprocessor perform integer arithmetic, which is to use it in a preprocessor condition.
Note however that your examples are not integer arithmetic. I just checked, and gcc's preprocessor fails if you try to make it do float comparisons. I haven't checked whether the standard ever allows floating point arithmetic in the preprocessor.
Regular macro expansion does not evaluate integer expressions, it leaves it to the compiler, as can be seen by preprocessing (-E in gcc) the following:
#define ONEPLUSONE (1 + 1) #if ONEPLUSONE == 2 int i = ONEPLUSONE; #endif Result is int i = (1 + 1); (plus probably some stuff to indicate source file names and line numbers and such).
The code you wrote doesn't actually make the preprocessor do any calculation. A #define does simple text replacement, so with this defined:
#define PI 3.1416 #define OP PI/100 This code:
if (OP == x) { ... } becomes
if (3.1416/100 == x) { ... } and then it gets compiled. The compiler in turn may choose to take such an expression and calculate it at compile time and produce a code equivalent to this:
if (0.031416 == x) { ... } But this is the compiler, not the preprocessor.
To answer your question, yes, the preprocessor CAN do some arithmetic. This can be seen when you write something like this:
#if (3.141/100 == 20) printf("yo"); #elif (3+3 == 6) printf("hey"); #endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With