Aaaaaaaa Aaaaaaaa - 1 month ago 9
C++ Question

How to make this initialization legal in C++?

I'va seen an excersise in a book, but I cannot figure out the answer:

Is the following code legal or not? If not, how might you make it

int null = 0, *p = null;

Of course, the second one is not legal, you cannot convert int to int*.

The theme was in the section the

GUYS! This is just an exercise about pointers, consts, and constexprs! I think, you have to solve it without cast and nullptr.


In C++11, a null pointer constant was defined as

an integral constant expression prvalue of integer type that evaluates to zero

(C++11 [conv.ptr] 4.10/1)

This means that adding constexpr to the declaration actually makes null a valid null pointer constant:

constexpr int null = 0, *p = null;

Note that this was considered a defect and changed in C++14, so that only an integer literal can be a null pointer constant:

A null pointer constant is an integer literal with value zero ...

(C++14 N4140 [conv.ptr] 4.10/1)

So, there is a way to make the initialisation legal using constexpr in C++11, but its existence was considered a standard defect and removed in C++14. The book is therefore teaching outdated information.

Note that because this is a defect, compilers have generally backported this behaviour to their C++11 mode as well (if they even implemented the original one in the first place).