0

I often have this kind of statement in my code :

(b != 0) ? a / b : a

In terms of speed and best C++ pratice, is it better to do a function

float divifnotzero(a,b) { ... return ... }

or a preprocessor macro like this ?

#define divifnotzero(a,b) ((b!=0)?a/b:a)
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 5
    With this being defined as an inline function, this should not matter with modern, highly optimizing, compilers. – Sam Varshavchik Jul 08 '16 at 00:21
  • Profile - it's really the best way. Really, for a divide, unless you're taking the zero branch a lot, the division is going to dominate any other overhead - that or other things that have nothing to do with macro vs. function (cache stalls, branch misprediction, etc). – J... Jul 08 '16 at 00:30
  • The optimizer will most likely make both solutions result in very similar binaries -- if not exact the same. A lot of functions are inlined by the optimizer as it sees fit, you don't have to worry about this kind of micro optimization. – Havenard Jul 08 '16 at 00:36
  • 3
    One reason to use a function is that your macro is wrong. – chris Jul 08 '16 at 00:47
  • 2
    and it's wrong in at least two ways. – Lightness Races in Orbit Jul 08 '16 at 00:56
  • `divifnotzero(a++,b++)` works as function. Macro, not so much. – user4581301 Jul 08 '16 at 01:07
  • @chris what's wrong? It works here: http://cpp.sh/9oaad – Basj Jul 08 '16 at 01:20
  • @Basj What if `divifnotzero(w + x, y / z)`? – Ripple Jul 08 '16 at 01:32
  • @Basj see http://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-c-c-macros – Jesper Juhl Jul 08 '16 at 05:28

2 Answers2

9

The pre-processor is just going to replace the code wherever you use the macro, so there is no difference there. As for a function, your compiler will almost certainly inline it, so again there should be no difference in speed. So, given that I would go with a function for readability.

1

Preprocessor macros inline any code you put in them. A function call allows you to reduce the size of the executable at the expense of some slight overhead. Based solely on that, in this instance you would want to use a preprocessor macro.

In practice, functions can be inlined just like preprocessor macros with the inline keyword, which gets rid of the overhead. The compiler can generally decide on whether or not to inline a function itself; one like this would almost certainly have that happen. Go for the function call, unless you're specifically compiling the program without optimizations while still valuing speed.

budjmt
  • 135
  • 1
  • 9