A
A
Artem2022-01-06 17:59:48
C++ / C#
Artem, 2022-01-06 17:59:48

Is data represented as bits in cells from right to left or from left to right?

In other words, the lower bits in the cells go to the left or right

#include <iostream>
#include <typeinfo>

using namespace std;

int main()
{
  setlocale(0, "");
  
  long x = 20;

  long *pi = &x;
  short *ps = reinterpret_cast<short*>(&x) + 1;

  cout
  << (static_cast<void*>(pi) == ps) << '\n';
  cout
  << pi << '\n'
  << ps << '\n'
  << *pi << '\n'
  << *ps << '\n';

  return 0;
}

output:
0 // false
0x3bfdcc
0x3bfdce
20
0

Or is it because the address, which is greater than the other, is actually not "to the right", but "to the left"?
*ps is equal to zero, even if you subtract one from ps, and if you add or subtract more than one, then a random value. It is equal to twenty, only if nothing is added

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2022-01-06
@Trame2771

The correct answer is neither. No way. Compare pointers not from the same array - undefined behavior. It was recently in an article on Habré. They refer to section 3.3.8, "Relational operators".
Moreover, you still have UB in your program: you cannot access data in a long variable through a short pointer - This is a violation of strict aliasing.
Thus, your program can output anything, depending on the compiler version and settings.
In practice, there are no left and right there, there are only minor and major addresses, read about big / little endian byte orders. They are there and so and so in different architectures. On x86, for example, the low byte has the lower address.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question