14

In C++ there is an aliasing loophole which allows the object representation of any object to be read or written through some pointers of character type.

Does this apply only to char and unsigned char or also to signed char?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
BeeOnRope
  • 60,350
  • 16
  • 207
  • 386

1 Answers1

19

No, the provision does not extend to signed char.

[basic.lval]

8 If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • [...]
  • a char, unsigned char, or std​::​byte type.

The quote above contains the very last bullet that pertains to aliasing with character types. signed char is excluded.

Nevertheless, this is also part of the subject CWG Issue 350 deals with, and so may change. Given the direction the issue has taken, the intent is for it to be (eventually, hopefully?) well-defined.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 1
    That's quite interesting. Why is `char` allowed, which is signed on my machine, but not `signed char`? But that's probably the reason why they want to add it in an upcoming standard. – mch Aug 26 '19 at 08:10
  • @mch - Could be an editorial mistake. I can only guess, really. – StoryTeller - Unslander Monica Aug 26 '19 at 08:13
  • 6
    @mch It's because in some cases, the standard does not allow `char` to be signed. For example, trap representations are allowed in all signed types, so a `signed char` may not be able to represent every byte, and `char` would have to be unsigned. – Artyer Aug 26 '19 at 09:31
  • 5
    @Artyer - Can't believe I forgot that. Though it's worth noting that with C++20 moving towards "2's complement only", `signed char` no longer has place for trap values http://eel.is/c++draft/basic.fundamental#7. – StoryTeller - Unslander Monica Aug 26 '19 at 09:37
  • I guess the `char` is left from C compatibility? Just like the entire `char` type :D – Antti Haapala -- Слава Україні Aug 26 '19 at 17:19
  • @AnttiHaapala: The Standard deliberately omitted any aliasing guarantees that wouldn't be meaningful on every machine, since they expected that implementations whose customers would find additional constructs useful would support them regardless of whether the Standard required them to do so. Unfortunately, a popular myth centers around the idea that the Standard was intended to deprecate all constructs for which support is not mandated, even though the authors published a Rationale which expressly denies such intent. – supercat Sep 01 '19 at 03:55