itg0w
itg0w

Reputation: 13

Why -1 equals 4th byte of integer -5?

Why does this code deduce a true (or 1 without std::boolalpha)

   char* arr = new char[4];
   int* i = new (arr) int(-5);
   char c = -1;
   std::cout << std::boolalpha << (arr[3] == c) << std::endl; 

Upvotes: 0

Views: 86

Answers (2)

eerorika
eerorika

Reputation: 238401

Why does this code deduce a true

Depending on the system used to run the program, the output could be either true or false, or behaviour of the program could be undefined.

On systems where negative numbers are represented using two's complement (which is very common, and will be guaranteed since C++20) and where byte-endianness is little endian (which is somewhat common on desktop systems; not so much elsewhere) and where the size of int is exactly 4, it just so happens that the byte arr[3] has the value -1. An example of CPU architecture where all of these conditions match is x86 a non-matching example is AVR32.

On big endian systems, this would not be the case and output wouldn't be true. And on systems where the size of int is less than 4 bytes, the byte could be uninitialised in which case output could be either true or false. In case where size of int is greater than 4 bytes, the behaviour of the program would be undefined.

Upvotes: 1

Logicrat
Logicrat

Reputation: 4468

If you inspect arr in a debugger you will probably see that it has the value 0xfbffffff. This will be true if your computer uses little-endian byte order, in which the least significant byte is stored at the lowest address. For your code to execute as you seem to expect, you should be examining arr[0]. Also, your code as written would probably execute as you expect on a machine that uses big-endian byte order.

Upvotes: 0

Related Questions