Search code examples
c++variablesrelational

is there a simpler way to do: if(num1 > num2 && num1 > num3), for bigger list of variables to compare?


I'd like to know (just for knowing) if there is a way to execute the following instructions with simpler code: (C++)

if(a > b && a > c && a > d)

is it possible to replace it with something like this:

 if(a > b, c, d)

Solution

  • Use std::max(std::initializer_list<T>) from the <algorithm> header like follows:

    #include <iostream>
    #include <algorithm>
    
    int main()
    {
        if(4 > std::max({2,3,6}))
            std::cout << "greater\n";
        else
            std::cout << "not greater\n";
    }