简体   繁体   中英

Operator comma in C++ ?: conditional

Could you tell me what's the problem with ?: operator it tells error:

 C2446: ':' : no conversion from 'int' to 'std::basic_ostream<_Elem,_Traits>'   
           c:\documents\visual studio 2005\projects\8.14\8.14\8.14.cpp  36

The Code:

int _tmain(int argc, _TCHAR* argv[])
{
int B;
int A=(6,B=8);
bool c = true;
cout << endl << B;
while (B != 100)
{
cout << "qgkdf\n";
(A<B) ? (c = 100, B=100, cout << "!!!") : (A = 100);
A--;
}
_getch();
return 0;
}

The types of the 2 operands of the conditional operator needs to be the same.

(A<B) ? (c = 100, B=100, cout << "!!!") : (A = 100);

The type of c = 100, B=100, cout << "!!!" is the type of cout << "!!!", which is std::ostream .

The type of of A = 100 is int .

These 2 types do not match, hence the error.

EDIT: The comma operator returns the value of the last part. You cann add an int, for example:

(A<B) ? (c = 100, B=100, (cout << "!!!"), 42) : (A = 100);
//                                      ^^^^

Live example here .

If you are going to write obfuscated code, make sure you know how to use casts, as the solution is obviously to cast the result of cout << "!!!"to an int :

(A<B) ? (c = 100, B=100, reinterpret_cast<int>(cout << "!!!")) : (A = 100);

As the return value is not being used it might be clearer to cast both sides to void.
Although not as clear as just using a good old "if".

This is blatant abuse of the ?: operator. Use an if statement. That's what they're for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM