compile-time conversion of floating-point expressions to long longs

Jim Cromie
Sun May 7 19:47:00 GMT 2006

Nelson H. F. Beebe wrote:
> Jim Cromie <> asks on Wed, 03 May 2006 12:17:38 -0400:
>>> ...
>>> Are there any macros that can tear into a floating point number and
>>> pull out the exponent and mantissa ?
>>> ...
> Yes, the C89 and C99 ISO C Standards include ldexp(x,n), which forms x
> * 2**n, and "f = frexp(x,&n);", which returns the fraction as a value
> in [1/2,1) (or 0 if x is zero) and the exponent of 2 in n.  Both are
> exact, and can be implemented reasonably efficiently.

yes, frexp() is almost what I want.
heres basically what I tried to do with it:

#include <stdio.h>
#include <math.h>
#include <float.h>

/* evaluate these constants at compile-time ?!? */
float f = 3.14159 * 2 * 100;
int myexp;
double mant = frexp(f,&myexp);

int main(int c, char** v)
    printf("float %g mantissa %f exp %d \n", f, mant, myexp);

as Id feared, it wouldnt compile;
$ make fp-comp
cc -g    fp-comp.c   -o fp-comp
fp-comp.c:37: error: initializer element is not constant
make: *** [fp-comp] Error 1

Im guessing its referring to myexp, the addy of which is passed.
This seems to foul up the constant-folder / compile-time evaluator,
but maybe this just wont work on more fundamental grounds.

If the problem is the 2nd arg being modified during evaluation,
then Id consider trying to split the function into 2 separate ones,
(since its compile-time, I dont care about evaluation cost of 2 calls),
but again, I think im oversimplifying.

IOW, I suspect that the compiler just wont call the function for me at 
and fold the constant into the code for me.  Id love to hear differently.
It also sounds like a rather unique requirement that would be tossed 
with scorn.


More information about the Gcc-help mailing list