llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[[nodiscard]] on numeric_limits functions

Open beached opened this issue 2 years ago • 8 comments

Would it be welcome to others to add [[nodiscard]] to the static methods on numeric_limits. It would help point out bugs like

if( lhs == std::numeric_limits<T>::min( ) and rhs == T{ -1 } ) {
  std::numeric_limits<T>::max( ); /* oops, ignored it */
}

beached avatar Mar 02 '24 22:03 beached

The standard doesn’t specify that they’re [[nodiscard]], so I’m not sure we can just do that...

Sirraide avatar Mar 02 '24 22:03 Sirraide

I thought implementors had freedom here, I can try and find it as it's not in the obvious place [dcl.attr.nodiscard]

beached avatar Mar 02 '24 22:03 beached

The MSVC STL implementation has [[nodiscard]].

MagentaTreehouse avatar Mar 02 '24 23:03 MagentaTreehouse

I guess the issue is that

#include <limits>

int main() {
    std::numeric_limits<int>::max( );
}

doesn't warn with -Wunused But

#include <limits>

int main( ) {
  5;  // warns
  auto a = std::numeric_limits<int>::max( ); // warns
}

does warn.

beached avatar Mar 02 '24 23:03 beached

It's absolutely fine to add [[nodiscard]] in places where the standard doesn't add it. Its only job is it to make the compiler produce a warning, which the standard has no constraints or requirements on. Libc++ has _LIBCPP_NODISCARD_EXT for cases which aren't in the standard.

philnik777 avatar Mar 03 '24 11:03 philnik777

Ah yeah, that’s true; I guess I just wasn’t sure because it’s a standard attribute, but it also makes sense that it would be fine.

Sirraide avatar Mar 03 '24 11:03 Sirraide

P3122R0 "[[nodiscard]] should be Recommended Practice" suggests to make these things recommended practice. (The author of the paper is the maintainer of libstdc++.) If that gets accepted we probably want to consider adding [[nodiscard]] in more places unconditionally and even removing _LIBCPP_NODISCARD_EXT.

mordante avatar Mar 03 '24 13:03 mordante

Another interesting tidbit, had the static constexpr function been consteval(non-addressable function anyways) it will warn. But only clang, not gcc/msvc

template<typename>
struct limits;

template<>
struct limits<int> {
    static constexpr int foo( ) { return 5; }
    static consteval int bar( ) { return 6; }
};

int main() {
    limits<int>::foo( );   // no warning
    limits<int>::bar( ); // -Wunused-value warning
}

beached avatar Mar 04 '24 15:03 beached