Mehrdad Mehrdad - 23 days ago 10
C++ Question

Why is C++ allowing me to assign a const char to a const char *?​!

To my astonishment, this compiles:

const char* c_str()
{
static const char nullchar = '\0';
return nullchar;
}


and it introduced a bug in my code. Thankfully, I caught it.

Is this intentional by C++, or a compiler bug? Is there a reason why the data type is actively ignored?

It worked in Visual C++ 2010 and GCC, but I don't understand why it should work, given the obvious data type mismatch. (The
static
isn't necessary, either.)

Answer

As you've defined it, nullchar is an integer constant expression with the value 0.

The C++03 standard defines an null pointer constant as: "A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero." To make a long story short, your nullchar is a null pointer constant, meaning it can be implicitly converted and assigned to essentially any pointer.

Note that all those elements are required for that implicit conversion to work though. For example, if you had used '\1' instead of '\0', or if you had not specified the const qualifier for nullchar, you wouldn't get the implicit conversion -- your assignment would have failed.

Inclusion of this conversion is intentional but widely known as undesirable. 0 as a null pointer constant was inherited from C. I'm fairly sure Bjarne and most of the rest of the C++ standard committee (and most of the C++ community in general) would dearly love to remove this particular implicit conversion, but doing so would destroy compatibility with a lot of C code (probably close to all of it).