1

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?

10
  • 3
    The 2nd one doesn't compile on my machine. JakeSchmidt.cpp:3:32: error: cannot initialize an array element of type 'char' with an rvalue of type 'nullptr_t. Commented May 26, 2020 at 1:35
  • Are you using MSVC? Both gcc and clang can't compile. Commented May 26, 2020 at 1:35
  • @songyuanyao I'm using built in gcc 9.3 on ubuntu Commented May 26, 2020 at 1:36
  • probably just a compiler bug then Commented May 26, 2020 at 1:37
  • 1
    Okay -- mystery solved. I have gcc 7 and 10 to test on. Seems there was some sort of regression in gcc 9. Commented May 26, 2020 at 1:59

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.