C++ Quiz127 of 173
Difficulty:
⬅️ Prev: 264Quiz ID: 265Next: 273 ➡️

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

#include <iostream>

void f(char*&&) { std::cout << 1; }
void f(char*&) { std::cout << 2; }

int main() {
    char c = 'a';
    f(&c);
}
Hint

c is an lvalue char. &c is a pointer to c, but is that pointer itself an lvalue or an rvalue?

Reveal answer

1

Explanation

c is an lvalue char. &c returns a pointer to the lvalue c, but that pointer itself is an rvalue, since it's just a nameless temporary returned from operator&. §[expr.unary.op]¶3:

The operand of the unary & operator shall be an lvalue of some type T. The result is a prvalue.

The first overload of f takes an rvalue reference to char *, the second takes an lvalue reference to char*. Since the pointer is an rvalue, the first overload is selected, and 1 is printed.

⬅️ Prev: 264Quiz ID: 265Next: 273 ➡️