Jake Schmidt
Jake Schmidt

Reputation: 1699

Why can char be initialized to nullptr in a std::array, but not by itself?

This code doesn't compile (using gcc 9.3)...

int main() {
    char bar = nullptr; //error: cannot convert ‘std::nullptr_t’ to ‘char’ in initialization
}


But this code does compile...

#include <array>
int main() {
    std::array<char, 1> foo = {nullptr}; // foo[0] == char(0), why?
}


Why is there a distinction?

Upvotes: 1

Views: 177

Answers (1)

eerorika
eerorika

Reputation: 238461

Why can char be initialized to nullptr in a std::array

It can't. The shown program is ill-formed in C++.

When an ill-formed program compiles, there are typically two possibilities:

  1. It is a language extension.

  2. It is a compiler bug.

In this case, I think it is the latter. The bug reproduces in GCC 9, but appears to have been fixed in GCC 10.

Upvotes: 5

Related Questions