5

I tried to replicate this but it would not compile.

unsigned char x = 0;
reinterpret_cast<signed char>(x);

It says

C:\Users\SXG5558\Documents\Arduino\sketch_jun30a\sketch_jun30a.ino: In function 'void setup()':

sketch_jun30a:3: error: invalid cast from type 'unsigned char' to type 'signed char'

     reinterpret_cast<signed char>(x);

                                    ^

exit status 1

EDIT:

To be clear, I really do want to reinterpret the bits in memory from signed to unsigned. I am writing an I2C library that reads and writes unsigned data, but I am using that library to control sensors which are signed, so I want to reinterpret cast the actual data.

Community
  • 1
  • 1
charmoniumQ
  • 5,214
  • 5
  • 33
  • 51

1 Answers1

5

The relevant part from cppreference.com is

Type aliasing

When a pointer or reference to object whose dynamic type is DynamicType is reinterpret_cast (or C-style cast) to a pointer or reference to object of a different type AliasedType, the cast always succeeds, but the resulting pointer or reference may only be used to access the object if one of the following is true:

[...]

  • AliasedType is the (possibly cv-qualified) signed or unsigned variant of DynamicType

[...]

ie. you forgot the & from the example you linked.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 1
    I can't believe I missed that. Thanks for answering a stupid question. – charmoniumQ Jul 01 '16 at 00:06
  • @Sam actually it is not such a stupid question. I needed some time to understand why it does not work without the `&` and I still could not explain it... – 463035818_is_not_an_ai Jul 01 '16 at 08:21
  • I think it is so that assignment goes through properly (eg. `reinterpret_cast(x) = 10`). That begs the question, what if you don't want this functionality? How can you cast `reinterpret_cast(f())` without assigning the result of `f()` to a temporary variable. – charmoniumQ Jul 01 '16 at 14:21