Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this initialization legal in C++?

Tags:

c++

c++11

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 legal?

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 constexpr.

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

like image 641
Aaaaaaaa Avatar asked Dec 05 '22 16:12

Aaaaaaaa


2 Answers

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).

like image 180
Angew is no longer proud of SO Avatar answered Dec 14 '22 23:12

Angew is no longer proud of SO


The other answer miss a very simple solution to make it legal: Make null a pointer:

int *null = 0, *p = null;

But as noted, the best solution is to not use the null variable at all, but to use the standard nullptr.

like image 41
Some programmer dude Avatar answered Dec 14 '22 23:12

Some programmer dude