Using C preprocessor concatenation to get exponential notation numbers

Why code:

#define EXPONENT(num, exp) num ## e ## exp EXPONENT(1,1) EXPONENT(1,-1) EXPONENT(1,+1) 

after pre-processing it changes to:

 1e1 1e- 1 1e+ 1 

not in

 1e1 1e-1 1e+1 

? I suspect this may be because -1, + 1 are parsed as two tokens (?). However, how then to get the last result?

+8
c-preprocessor concatenation
source share
3 answers

You are right, -1 and +1 are two preprocessing tokens, so only the first is inserted into e .

For me

 #define EXPO(num, sign, ex) num ## e ## sign ## ex EXPO(1,,1) EXPO(1,-,1) EXPO(1,+,1) 

worked with gcc-4.5.1.

+4
source share

I think the problem you are facing is seen as undefined behavior. Per gcc 4.3.2 concatenation documentation :

However, two tokens that do not form a valid token cannot be glued together. For example, you cannot combine x with + in either order. If you try, the preprocessor issues a warning and emits two tokens. Is this a space between undefined tokens. It is generally accepted to find unnecessary use of ## in complex macros. If you get this warning, it is likely that you can simply remove the `## '.

See also this answer to SO which shows the same problem.

Edit:

I managed to get this to work, but you will need two macros for + and -

 #define E(X) 1e-##X int main() { double a = E(10); // expands to 1e-10 printf("%e", a); return 0; } 
+3
source share
 #include <stdio.h> #include <stdlib.h> #define EXPONENT(num, exp) atof(#num "e" #exp) void main(){ double x = EXPONENT(1,-1); printf("%f", x); } 
-one
source share

All Articles