Is there a way to convince the C preprocessor to evaluate a transcendental function of a constant at compile-time?
For example, replace (int)256*sin(PI/4) with 181. This will help me keep magic numbers out of my code.
If it makes a difference, I’m using MSPGCC 4.5.3 and I have no sin() or cos() available at runtime.
As long as your arguments are all within the range [-π/4,+π/4], you can use the same formula standard implementations of libm use to compute sin. It’s correct up to the last place (at most 1ulp error) just like the IEEE standard requires:
Source: http://www.netlib.org/fdlibm/k_sin.c
While not what I’d call pleasant, you definitely can convert that whole function into a macro that will evaluate to a (compile-time) floating point constant expression. (Ignore the bit hackery at the beginning that has nothing to do with the value, and as far as I know you should assume
iyis 0.)