Displaying two different data types with operator ?

J

John Smith

How do I use two different data types with a conditional operator ?

I want to cout either a character or an integer depending on a
certain condition.

cout << ((IsThisTrue? char:integer)

The compiler seems to treat the char as an integer. The program
prints out the decimal value of the char.
 
K

Kaz Kylheku

John said:
How do I use two different data types with a conditional operator ?

I want to cout either a character or an integer depending on a
certain condition.

cout << ((IsThisTrue? char:integer)

You can't use the name char as an identifier.
The compiler seems to treat the char as an integer. The program
prints out the decimal value of the char.

An instance of the ternary conditional operator ?: constitutes a single
C++ expression. C++ is statically typed, and every expression can have
only one manifest type, which is determined at compile time as a
synthesized attribute from the types of its constituent expressions,
regardless of context.

In the case of the ternary expression, the type is determined from the
the second and third operands, which must either have the same type, or
it must be possible to convert them to a common type using the usual
arithmetic or pointer conversions. See the C++ standard for the exact
rules.

In the case of char and int, char value will be promoted to int, and
the overall expression will return type int no matter which way the
condition falls.

And that means that the ostream::eek:perator << (int) will be called on
the cout object regardless of the value of isThisTrue.

The ?: operator cannot dynamically select between two different
overloads of the << operator for int and char; it offers a single type
to overload resolution.

Your intent can be expressed as :

if (isThisTrue)
cout << character;
else
cout << integer;

You could design a programming language in which the conditional
operator will do that by itself, but C++ isn't it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top