a56444c a56444c - 1 month ago 15
C++ Question

Compact multi-conditional if statement

I have the simplest question ever. I was practising with the

if
statement and wondered if I could print out different messages under different conditions, but I wanted to keep it simple. If the 1st condition is true, the 1st line of
cout
will print; and if the 2nd condition is true, the 2nd line of
cout
will print; and so on. Code follows;

int x; cin >> x;
int y; cin >> y;

if(x<y||x>y||x==y)
{
cout << x << " is smaller than " << y << endl;
cout << x << " is bigger than " << y << endl;
cout << x << " is equal to " << y << endl;
}


Apparently there is something missing, some kind of
||
s between the
cout
s. Is it possible to keep this code as compact as it is and make it function properly?

Answer

What to you mean by simple? If compact, then this is correct (but not the most readable) . .

x==y?cout<<"x=y":(x<y?cout<<"x<y":cout<<"x>y");

. . or go crazy and make == the default case to save a char

x>y?cout<<"x>y":(x<y?cout<<"x<y":cout<<"x=y");
Comments