Suppose I have
#define DETUNE1 sqrt(7)-sqrt(5)
#define DETUNE2 sqrt(11)-sqrt(7)
And I call these multiple times in my program.
Are DETUNE1 and DETUNE2 calculated every time it is called?
Are DETUNE1 and DETUNE2 calculated every time it is called?
Very unlikely.
Because you are calling sqrt with constants, most compilers would optimize the call to the sqrt functions and replace it with a constant value. GCC does that at -O1. So does clang. (See live).
In the general case, if you have a macro with n being a runtime value:
#define DETUNE1(n) (sqrt(n)-sqrt(n))
then after the textual replacement, at least one of the sqrt functions will need to calculated.
Notice that your macro is not safe. You should have brackets around it to be safe. For example, as DETUNE1 * DETUNE1 would not produce what you expect.
Yes it will be calculated every time. Better you #define the calculated value. You need to also make sure that put these in brackets as it may give unexpected result.
e.g. If you are using in calculation as below :
int result = DETUNE1 * 4
then it will result in
int result = sqrt(7)-sqrt(5) * 4
So multiplication will be done before subtraction because of operator precedence in C
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