I have a simple function that I compile for C
in my operating code and for C++
in my tests. Since I’ll use this function extensively in my code, I’d like to declare it in a utility file and make it as efficient as possible.
Let’s consider an example function that calculates the absolute difference between two uint64_t
values.
Here are three options:
Option 1:
constexpr uint64_t diff(uint64_t a, uint64_t b)
{
return a > b ? a - b : b - a;
}
In C++, this function will be evaluated at compile time and implicitly inlined.
In C, constexpr
will be ignored, implying only that the return value of the function is constexpr
.
Option 2:
constexpr inline uint64_t diff(uint64_t a, uint64_t b)
{
return a > b ? a - b : b - a;
}
In C++, this function will be evaluated at compile time and implicitly inlined. The inline
keyword is redundant.
In C, constexpr
will be ignored, implying only that the return value of the function is constexpr
, and there is a hint to the compiler to switch the function with its body.
Option 3:
#define DIFF(a, b) ((a) > (b) ? ((a) - (b)) : ((b) - (a)))
In C++, it works, but using a constexpr
function can add type safety.
In C, it works, and it’s probably the most efficient way, as in an inline function, the compiler might ignore inline.
Which choice is better, and why? is there a fourth option?
Remember that I need to pick up the best choice for both c
and c++
.