Search code examples
c++conditional-statementsoperator-keywordternary

C++ conditional ternary operator


Lines 11, 12, 15 and 16 are getting errors: " invalid operands of types int and const char[2] to binary operator<< " (I removed the "`" so it wouldn't display it code format).

#include<iostream>

using namespace std;

int main(){

int md,dg,dd,mg,m,d;
cin >> md >> dg >> dd >> mg;

if (dd+dg==md+mg){
   cout << (mg>dg) ? 0 : 1 << " ";
   cout << (dg>mg) ? 0 : 1 << endl;
}
else{
      cout << (mg+md>dd+dg) ? 0 : (dd+dg-mg-md) << " ";
      cout << (dg+dd>md+mg) ? 0 : (md+mg-dg-dd) << endl;
}

system("pause");
}

Solution

  • You need to put parentheses around the ternary expression:

     cout << ((mg>dg) ? 0 : 1) << " ";
    

    Otherwise the input is interpreted as

     cout << (mg>dg) ? 0 : (1 << " ");
    

    due to operator precedence.