Stephanus Tavilrond Stephanus Tavilrond - 1 month ago 13
C++ Question

Is this valid usage of inline functions?

Let's say I have this code (don't mind the fact that SecondsToMinutes and MinutesToHours are carbon copies of each other)

inline float SecondsToMinutes(float seconds)
{
return seconds / 60.0;
}
inline float MinutesToHours(float minutes)
{
return minutes / 60.0;
}
inline float HoursToDays(float minutes)
{
return minutes / 24.0;
}
inline float SeconndsToHours(float seconds)
{
return MinutesToHours(SecondsToMinutes(seconds));
}
inline float MinutesToDays(float minutes)
{
return HoursToDays(MinutesToHours(minutes));
}
inline float SeconndsDays(float seconds)
{
return MinutesToDays(SecondsToMinutes(seconds));
}


Is this valid usage of inline? Does it make sense? Is this good practice? After all, if I recall correctly, inline means that function calls are replaced by function bodies, so

return MinutesToDays(SecondsToMinutes(seconds))


should be equivalent to

return seconds / 60.0 / 60.0 / 24.0


Right?

Or is it better to just use macros for this?

#define EXCHANGE_SEC_MIN(x) (x / 60.0)
#define EXCHANGE_MIN_H(x) (x / 60.0)
#define EXCHANGE_H_D(x) (x / 24.0)
#define EXCHANGE_SEC_H(x) (EXCHANGE_MIN_H(EXCHANGE_SEC_MIN(x)))
#define EXCHANGE_MIN_D(x) (EXCHANGE_H_D(EXCHANGE_MIN_H(x)))
#define EXCHANGE_SEC_D(x) (EXCHANGE_MIN_D(EXCHANGE_SEC_MIN(x)))


Which one is the better practice? Or neither is? I'd like others cents on this.

Answer

Is this valid usage of inline? Does it make sense?

Well, yeah but no.

It doesn't hurt anything at this point but doesn't do what you think it does either.

In an excellent post about inline deft_code correctly says :

It is said that inline hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.

So, it doesn't hurt anyone if you do it but the chance your compiler will listen to your hint is practically 0. If it sees fit to inline the code, it will do so itself.

inline nowadays is used mostly for the linker since it allows multiple definitions in multiple compilation units.

If you want to make sure your code is as fast as possible and you have access to C++11 you should use constexpr:

constexpr float SecondsToMinutes(float seconds)
{
    return seconds / 60.0;
}
//etc..
Comments