0

I am using C++14. Size of int is 4 bytes.

Here is my code:

#include<iostream>
using namespace std;
int main()
{
  int a=4294967290;
  int b=-6;
  if(b==a)
  cout<<"Equal numbers";
}

This is giving output as Equal numbers, that means 4294967290 is equal to -6 in memory in binary format. Then how are large positive numbers distinguished from negative numbers? Is this only with C++ or with any other programming language?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Raj
  • 11
  • 1
    The range for an unsigned int is 0 to 4,294,967,295, but int (which is signed) is -2,147,483,648 to 2,147,483,647. – GRW Mar 12 '21 at 05:32
  • 1
    As a general tip, crank up the warnings on your compiler until it complains about that. Both clang and gcc issue a warning for that line (in fairness, gcc required more cranking) - https://gcc.godbolt.org/z/jj413z – Stephen Newell Mar 12 '21 at 06:30
  • 4294967290 is higher than 2147483647, the max value of a 32bit `int`, so the `int` overflows, which is *undefined behavior*, but the result will generally wrap to negative. – Remy Lebeau Mar 12 '21 at 07:30

1 Answers1

2

Bits is bits. What the bits mean is up to you.

Let's talk about 8-bit quantities to make it easier on us. Consider the bit pattern

   1 0 0 0  0 0 0 0

What does that 'mean'?

If you want to consider it as an unsigned binary integer, it's 128 (equals 2 to the 7th power).

If you want to consider it as a signed binary integer in twos-complenent representation, it's -128.

If you want to treat it as a signed binary integer in sign-and-magnitude representation (which nobody does any more), it's -0. Which is one reason we don't do that.

In short, the way large positive numbers are distinguished from negative numbers is that the programmer knows what he intends the bits to mean. It's something that does not exist in the bits themselves.

Languages like C/C++ have signed and unsigned types to help (by defining whether, for example, 1000 0000 is greater or less than 0000 0000), but there will always be pitfalls you need to be aware of, because integers in computer hardware are finite, unlike the real world.

user15187356
  • 807
  • 3
  • 3
  • "It's something that does not exist in the bits themselves." - at least not in anything modern enough for C++14. There's ancient hardware where types _did_ exist in hardware, famously the Burroughs B6xxx series – MSalters Mar 12 '21 at 11:15
  • True that, though I don't recall whether there was a distinction for signed/unsigned integers. – user15187356 Mar 12 '21 at 13:21