How to make this initialization legal in C ++?

I saw excersise in the book , but I can not understand the answer:

Is the following code legal or not? If not, how can you do this? legally?

int null = 0, *p = null;

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

The topic was in the section constexpr.

GUYS! This is just an exercise on pointers, consts and constexprs! I think you need to solve this problem without using cast and nullptr.

+4
source share
6 answers

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

integral constant expression prvalue of integer type, which evaluates to zero

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

, constexpr null :

constexpr int null = 0, *p = null;

, ++ 14, :

0...

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

, constexpr ++ 11, ++ 14. .

, , , ++ 11 ( ).

+9

, : null :

int *null = 0, *p = null;

, , null , nullptr.

+3

diff,

int null = 0, *p = nullptr;
                       ^^^

int null = 0, *p = {};

int null = 0, *p = 0;

, , ( ++ 14), 0. int.


, p, null address:

int null = 0, *p = &null;
+2

, :

int null = 0, *p = 0;

int null = 0, *p = nullptr;
+1

, :

int null = 0, *p = null;

:

int null = 0, *p = static_cast<int*>(null);

:

int null = 0, *p = (int*)null;
int null = 0, *p = reinterpret_cast<int*>(null);

, .

C- (int*)null ++ ( , - ), , ( ) / ( , ?).

reinterpret_cast , , , C-, , , .

, ++ 11 :

int null = 0, *p = nullptr;
+1

I think you can use reinterpret_cast<int*>int to make it valid.

-1
source

Source: https://habr.com/ru/post/1661849/


All Articles