Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Parameterized Macros

I can' figure out what is the advantage of using

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

instead of

 float CRANDOM() {
    return random() / 2.33;
}
like image 991
foho Avatar asked Dec 16 '22 02:12

foho


2 Answers

By using a #define macro you are forcing the body of the macro to be inserted inline.

When using a function there will1 be a function call (and therefor a jump to the address of the function (among other things)), which will slow down performance somewhat.

The former will most often be faster, even though the size of the executable will grow for each use of the #defined macro.


  • greenend.org.uk - Inline Functions In C

1a compiler might be smart enough to optimize away the function call, and inline the function - effectively making it the same as using a macro. But for the sake of simplicitly we will disregard this in this post.

like image 103
Filip Roséen - refp Avatar answered Dec 20 '22 12:12

Filip Roséen - refp


It makes sure that the call to CRANDOM is inlined, even if the compiler doesn't support inlining.

like image 24
orlp Avatar answered Dec 20 '22 11:12

orlp