Ruslan
Ruslan

Reputation: 19120

Why is a ternary conditional avoided in libstdc++ implementation of std::max?

In libstdc++ implementation of the <algorithm> header, part of which on my system resides in /usr/include/c++/8/bits/stl_algobase.h, I can see the following implementation of std::max:

template<typename _Tp>
  _GLIBCXX14_CONSTEXPR
  inline const _Tp&
  max(const _Tp& __a, const _Tp& __b)
  {
    // concept requirements
    __glibcxx_function_requires(_LessThanComparableConcept<_Tp>)
    //return  __a < __b ? __b : __a;
    if (__a < __b)
      return __b;
    return __a;
  }

You can see that the single statement with the ternary conditional operator ?: is commented out, and the if-based code is used instead.

I suppose there's some technical reason for this. So what can go wrong with the commented out version and not with the active one? Or are they exactly equivalent, and the active version simply makes step-by-step debugging easier?

Upvotes: 2

Views: 99

Answers (1)

dewaffled
dewaffled

Reputation: 2973

There were conditional operator implementation bugs in gcc like https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53000. Probably this is to avoid those.

Upvotes: 2

Related Questions