-4

In C++, I can declare a variable as either an unsigned short or an unsigned char (with 2 bytes) as shown below. However, is there any differences?

unsigned short p;
unsigned char q[2];
Habibie
  • 11
  • 2
  • 3
    One thing to think about is that `short` is not guaranteed to be two bytes or 16 bits. – Some programmer dude Nov 02 '17 at 15:12
  • 4
    Any differences? Aside from the fact that they are totally different types? (array vs not an array, short vs char). – Borgleader Nov 02 '17 at 15:12
  • 4
    Also, *why* do you ask? What is the problem you're *really* trying to solve? – Some programmer dude Nov 02 '17 at 15:12
  • This is a very bad question. Please consult some basic materials about C++ before asking questions. – underscore_d Nov 02 '17 at 15:12
  • 1
    Endianess? A short is a multibyte quantity, and may be represented on some systems as Most Significant Byte (MSB) first or Least Significant Byte first (LSB). An array has no significant byte ordering. – Thomas Matthews Nov 02 '17 at 15:22
  • @ThomasMatthews I have shamelessly included your point in the answer. :) – wally Nov 02 '17 at 15:29
  • After reading all of your responses above, I started to realize perhaps it is safe to say the obvious difference is the former is a two bytes of integer while the later is a 2 bytes of chars. – Habibie Nov 02 '17 at 15:37
  • Yes. Simply try using these both to do things with numbers within the range of the `unsigned short` and see which one you find easiest. The difference will then be obvious. – underscore_d Nov 02 '17 at 15:58

1 Answers1

2

Differences:

  • Types are different. C++ is a strongly typed language and the compiler enforces the type checking.
  • Size might differ. We know that there is no padding between the elements, but these two variables might not have the same amount of memory, because the size of the short is platform dependent.
  • Endianess. A short is a multibyte quantity, and may be represented on some systems as Most Significant Byte (MSB) first or Least Significant Byte first (LSB). The char array has no significant byte ordering.
  • Alignment. The char array may not be allocated on one of the same alignment boundaries as a short.
  • Aliasing. The short may be casted to a char array so that it may be evaluated as an array of bytes, but the reverse is not allowed.
wally
  • 10,717
  • 5
  • 39
  • 72
  • 2
    2 more: Alignment and pointer aliasing. This is why taking a pointer to a char array and casting it to pointer-to-whatever is very very forbidden. – user2394284 Nov 02 '17 at 16:25