C++ Logo

STD-DISCUSSION

Advanced search

Subject: Re: Accessing an object with a char pointer.
From: Christopher Hallock (christopherhallock_at_[hidden])
Date: 2020-05-13 10:50:40


On Wed, May 13, 2020 at 10:03 AM yo mizu via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1839r2.pdf
> 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
> char."
>
> 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
> architectures.
>

I agree that the Standard makes this example well-defined but,
accidentally, with nonsense semantics.

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

I think the lvalue-to-rvalue conversion and/or the aliasing provision of
[basic.lval]/11 <https://timsong-cpp.github.io/cppwp/expr#basic.lval-11> is
underspecified in this case, but it's kind of moot because we want the
Standard to say that reinterpret_cast<char*>(...) simply points to the
first byte to begin with.



STD-DISCUSSION list run by herb.sutter at gmail.com

Older Archives on Google Groups