Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator with mixed data types?

Conditional operator cannot work with mixed data types, so:

bool cond = true;
cout << (cond?1:2) << endl;
cout << (cond?"msg1":"msg2") << endl;
cout << (cond?1:"msg") << endl;

On the last line, I get this error message:

error: incompatible operand types ('int' and 'const char *')

Is there a way to mix different types in such a statement, using a single line of code? I need to put it inside a preprocessor macro.

Compiler: clang 3.5

like image 306
Pietro Avatar asked May 08 '26 20:05

Pietro


1 Answers

For the last statement you can determine the common type like std::string.

For example

std::cout << ( cond ? std::to_string( 1 ) : "msg" ) << std::endl;
like image 68
Vlad from Moscow Avatar answered May 10 '26 10:05

Vlad from Moscow