Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ / C #define macro calculation

Tags:

c++

c

macros

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?

like image 914
lppier Avatar asked Jul 31 '26 02:07

lppier


2 Answers

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.

like image 85
P.P Avatar answered Aug 02 '26 15:08

P.P


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

like image 31
Amol Saindane Avatar answered Aug 02 '26 16:08

Amol Saindane