0

I know there is a very similar question already: Ternary operator ?: vs if...else

This is more regarding returning bool literals from a function.

Given the following function:

bool inRange(size_t value, size_t upperBound) const
{
   return (value >= 0 && value < upperBound) ? true : false;
}

CLion advices me this can be simplified using an "if else" statement instead. Would this be actually faster because of return value optimization and/or likelihood of certain if branches? (or some other reason).

Or is it maybe a style guide given by CLion?

pg13
  • 1
  • 1
  • 2
    it's helpful if you post full message. – apple apple Jul 27 '22 at 17:00
  • The only way to know for sure is to measure both versions, but I suspect the assembly will be similar if not identical. – Stephen Newell Jul 27 '22 at 17:07
  • Simplifying code is subjective. It is usually concerned with make the code easier to read for mere mortals. Most modern compilers (if optimisation is enabled) will produce the same object code if you had written `if (value >= 0 && value < upperBound) return true; else return false;` - and a fair few people (and some formal style guides) deem that more readable. Personally, I would just do `return (value >= 0 && value < upperBound)` or (since `value` is unsigned) `return value < upperBound` - but that's ALSO a subjective judgement. – Peter Jul 27 '22 at 23:34

1 Answers1

5

The recommendation it is suggesting is to change

bool inRange(size_t value, size_t upperBound) const
{
   return (value >= 0 && value < upperBound) ? true : false;
}

to

bool inRange(size_t value, size_t upperBound) const
{
   return value >= 0 && value < upperBound;
}

this has nothing to do with performance, the ternary is simply redundant. I am quite positive it would compile to the same assembly (proof), the IDE is just suggesting you simplify your redundant logic.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • In addition, the `value >= 0` is also redundant for unsigned values. The compiler indeed did not generate code to check that. – prapin Jul 27 '22 at 17:50