C++ Logo


Advanced search

Subject: Accessing an object with a char pointer.
From: yo mizu (mizu2594_at_[hidden])
Date: 2020-05-13 09:03:01

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

STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups