Let's say I have the following in C or C++:
#include <math.h>
#define ROWS 15
#define COLS 16
#define COEFF 0.15
#define NODES (ROWS*COLS)
#define A_CONSTANT (COEFF*(sqrt(NODES)))
Then, I go and use NODES
and A_CONSTANT
somewhere deep within many nested loops (i.e. used many times). Clearly, both have numeric values that can be ascertained at compile-time, but do compilers actually do it? At run-time, will the CPU have to evaluate 15*16
every time it sees NODES
, or will the compiler statically put 240
there? Similarly, will the CPU have to evaluate a square root every time it sees A_CONSTANT
?
My guess is that the ROWS*COLS
multiplication is optimized out but nothing else is. Integer multiplication is built into the language but sqrt is a library function. If this is indeed the case, is there any way to get a magic number equivalent to A_CONSTANT
such that the square root is evaluated only once at run-time?