C - Parameterized Macros

I can find out what is the advantage of using

#define CRANDOM() (random() / 2.33); 

instead

  float CRANDOM() { return random() / 2.33; } 
+4
source share
5 answers

Using the #define macro , you force the inline macro body to be inserted.

When using a function, there will be 1 function call (and, therefore, transition to the function address (among other things)), which will slow down the work somewhat.

The first will most often be faster, although the size of the executable will grow for each use of the #defined macro.



1, the compiler can be smart enough to optimize a function call and embed a function — effectively make it the same as using a macro. But for the sake of simplicity, we will ignore this in this article.

+5
source

He makes sure that the CRANDOM call CRANDOM built-in, even if the compiler does not support embedding.

+3
source

Firstly, #define is incorrect due to the semi-colony at the end, and the compiler will break into:

 float f = CRANDOM() * 2; 

Secondly, I personally try to avoid using a preprocessor by not separating platform-independent sections in cross-platform code, and, of course, code reserved exclusively for DEBUG or non-DEBUG assemblies.

nightcracker correctly states that it will always be “efficiently” built-in, but if you can rewrite the function as inline , I don’t see the benefits of using the preprocessor version, unless the C compiler is built-in.

+3
source

The first is the old style. The only advantage of the first is that if you have a compiler that follows the old C90 standard, the macro will work as a built-in one. In a modern C compiler, you should always write:

 inline float CRANDOM() { return random() / 2.33f; } 

where the inline keyword is optional.


(Note that in floating point literals, there must be f at the end, otherwise you force the calculation to double, which is then implicitly rounded to float.)

+1
source

The function call includes a bit of overhead - clicking on the return address on the machine stack and branching in this case. By using a macro, you can avoid this overhead. Once upon a time, it was important; these days, many compilers will embed the body of a tiny function like this inline. In general, trying to trick the compiler into releasing faster code is a fool game; you often create something slower.

0
source

Source: https://habr.com/ru/post/1401586/


All Articles