Can someone explain to me this line of code?

I noticed my professors never taught me this.
Only dedicated, passionate programmers uses this

 
cout << ((a+b)%3 == 0 && 2*a >= b && 2*b >= a ? "YES":"NO");
Hello advancedip,

Furry Guy's link is good and a good place for reference, always better than the reference here. This might be a bit less technical to start with http://www.cplusplus.com/doc/tutorial/operators/#conditional

Another way to think about this is that it is a shorthand for an if/else statement.

E.G., if (condition) ? (then) something : (else) something else.

An example is:
1
2
3
4
5
6
int main()
{
    int days{};

    std::cout << "You have " << days << (days == 1 ? " day." : " days.");
}

Here the () tend to be needed.

Which is shorter and more useful than:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
    int days{};
    std::string word;

    if (days == 0)
    {
        word = " days.";
    }
    else
    {
        word = " days.";
    }

    std::cout << "You have " << days << word;
}


Hope that makes more sense now,

Andy
Topic archived. No new replies allowed.