468,110 Members | 1,522 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,110 developers. It's quick & easy.

Displaying two different data types with operator ?

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.
Oct 9 '05 #1
1 1841
John Smith wrote:
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::operator << (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.

Oct 9 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by Jon Weston | last post: by
7 posts views Thread by Arpan | last post: by
3 posts views Thread by jacob navia | last post: by
1 post views Thread by Solo | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.