1

I run into this when I tried to print a hexadecimal number by this sentence:

cout << (a > 9 ? (char)('A' + a - 10) : a);

However, when a > 9, it prints an integar, not a char. but

cout << (char)('A' + a - 10);

worked well. Why things go like that? How can I solve it? Thanks for any hint.

Barmar
  • 741,623
  • 53
  • 500
  • 612
L.Amanda
  • 11
  • 2

2 Answers2

4

The type of an expression is determined at compile time, it can't depend on runtime conditions. When the two resulting expressions in a conditional (aka tertiary) expression are different, they have to be converted to a common type, and this is the type of the expression as a whole. See Return type of '?:' (ternary conditional operator) for the details.

In your case, a is presumably int, and (char)('A' + a - 10) is char, so the common type is int, so cout uses its method for printing int rather than char.

Instead of a tertiary, use an ordinary if:

if (a > 9) {
    cout << static_cast<char>('A' + a - 10);
} else {
    cout << a;
}

Or cast to char after doing the conditional.

cout << static_cast<char>(a > 9 ? ('A' + a - 10) : ('0' + a));
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • A possibly better conversion would be `cout << (char)(a > 9 ? 'A' + a -10 : '0' + a)`. In other words, allow the `?:` operator to consistently give a result of type `int`, and convert that to `char`. – Peter Apr 28 '18 at 09:38
  • Better use a `static_cast` than a C style cast, so as to not teach Bad Programming Habits™. Or if you value the conciseness of a C style cast, express it in C++ syntax like `char( expr )`, which is both shorter and less visually noisy. – Cheers and hth. - Alf Apr 28 '18 at 09:44
-1

Try this

cout << (char)(a > 9 ? ('A' + a - 10) : a + '0');

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
Tanveer Badar
  • 5,438
  • 2
  • 27
  • 32
  • That will print control characters instead of single digits. `(char) 3` is `'\3'`. – Barmar Apr 28 '18 at 08:59
  • @Barmar: fixed that. – Cheers and hth. - Alf Apr 28 '18 at 09:05
  • @Tanveer: better use a `static_cast` than a C style cast, so as to not teach Bad Programming Habits™. Or if you value the conciseness of a C style cast, express it in C++ syntax like `char( expr )`. – Cheers and hth. - Alf Apr 28 '18 at 09:06
  • 3
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made. – rollstuhlfahrer Apr 28 '18 at 14:20