C++ Logo


Advanced search

Accessing an object with a char pointer.

From: yo mizu <mizu2594_at_[hidden]>
Date: Wed, 13 May 2020 23:03:01 +0900
According to P1839R2, the following code has undefined behavior as per
[expr.pre] p4.

int a = 420;
char b = *reinterpret_cast<char*>(&a);

P1839R2 states, "When the lvalue-to-rvalue conversion is applied to
the initializer expression of b, the behavior is undefined as per
[expr.pre] p4 because the result of such a conversion would be the
value of the int object (420), which is not a value representable by

So is the behavior of the other example below defined?

int c = 4;
char d = *reinterpret_cast<char*>(&c);

The result of the lvalue-to-rvalue conversion would be the value of
the int object (4).
It is not an object of char, but the value of 4 can be represented by char.

If this behavior is defined, and the value of "d" is 4, I think it is
at odds with the behavior of many existing compilers for big endian

And how about the following example.

struct E {} e {};
char f = *reinterpret_cast<char*>(&e);

Is the behavior of this example defined?
If this is undefined behavior, what description in the standard is it based on?

Thank you and best regards,
Yo Mizu

Received on 2020-05-13 09:06:14