C++ Quiz47 of 173
Difficulty:
⬅️ Prev: 116Quiz ID: 118Next: 119 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>

void print(char const *str) { std::cout << str; }
void print(short num) { std::cout << num; }

int main() {
  print("abc");
  print(0);
  print('A');
}
Hint

Which type should 0 be converted to? Is one conversion better than the other?

Reveal answer

The program has a compilation error

Explanation

Sneaky ambiguous function call.

The statement print(0); is ambiguous due to overload resolution rules. Both print functions are viable, but for the compiler to pick one, one of them has to have a better conversion sequence than the other. §[over.match.best.general]¶3:

If there is exactly one viable function that is a better function than all other viable functions, then it is the one selected by overload resolution; otherwise the call is ill-formed.

(a) Because 0 is a null pointer constant [1], it can be converted implicitly into any pointer type with a single conversion.

(b) Because 0 is of type int, it can be converted implicitly to a short with a single conversion too.

In our case, both are standard conversion sequences with the same conversion rank (§[over.ics.rank]¶4). Since no function is better than the other, the call is ill-formed.

[1] §[conv.ptr]¶1:

A null pointer constant is an integer literal (§[lex.icon]) with value zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type (...).

⬅️ Prev: 116Quiz ID: 118Next: 119 ➡️