C++ has a standard function isinf()? like isnan()?
If yes, it returns true in case of +inf and -inf also?

Dani AI

Generated

Short answer for : modern C++ (since C++11) provides std::isinf in <cmath>, and it detects both positive and negative infinity. (en.cppreference.com)

A compact, idiomatic check that also tells you the sign uses std::isinf together with std::signbit (and std::isnan for NaN):

#include <cmath>
#include <iostream>

void report(double x) {
    if (std::isinf(x)) {
        std::cout << (std::signbit(x) ? "-inf\n" : "+inf\n");
    } else if (std::isnan(x)) {
        std::cout << "NaN\n";
    } else {
        std::cout << "finite\n";
    }
}

Use std::signbit to distinguish +/−; std::isnan is available too. (en.cppreference.com)

If you must support pre-C++11 compilers (or environments where the C++ wrappers are missing), a safe fallback is to test against std::numeric_limits<T>::infinity() for both signs — but first check has_infinity. The template isinf posted by only checks positive infinity; extend it to also test -std::numeric_limits<T>::infinity() or prefer the std::isinf + std::signbit approach when available. (en.cppreference.com)

A few portability notes: the C macro isinf (C99/POSIX) is implementation-defined about the exact return value (POSIX/glibc historically return 1 for +Inf and −1 for −Inf, but C99 only guarantees a non‑zero for “infinite”). On Windows older MSVC releases lacked the C99/C++11 wrappers (they were added later), so you may need compiler-specific helpers there. (en.cppreference.com)

Best practice: target std::isinf/std::isnan/std::signbit in modern code; add a tiny numeric_limits-based fallback for older toolchains.

Recommended Answers

All 3 Replies

isnan() is from C99; and is not part of C++98. See http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.15
In C++0x, isnan() is part of TR1.

You could easily roll out isnan() and isinf() on your own, though:

#include <limits>

template< typename T > inline bool isnan( T value )
{ return value != value ; }

template< typename T > inline bool isinf( T value )
{
    return std::numeric_limits<T>::has_infinity &&
           value == std::numeric_limits<T>::infinity() ;
}

and I have to check -inf also, i think!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.