-2

I want to know how the unsigned integer works.

#include <iostream>
using namespace std;

int main(){
    int a = 50;             //basic integer data type
    unsigned int b;         //unsigned means the variable only holds positive values
    cout << "How many hours do you work? ";
    cin >> b;
    cout << "Your wage is " << b << " pesos.";

}

But when I enter -5, the output is

Your wage is 4294967291 pesos.

And when I enter -1, the output is

Your wage is 4294967295 pesos.

Supposedly, unsigned integers hold positive values. How does this happen? And I only know basic C++. I don't understand bits.

  • 2
    Possible duplicate of [C/C++ unsigned integer overflow](https://stackoverflow.com/questions/16056758/c-c-unsigned-integer-overflow) – lubgr Aug 14 '18 at 14:10
  • 3
    "_Supposedly, unsigned integers hold positive values_" Sure, they hold positive values. Your output is positive, so why do you think, that unsigned integers hold anything more, than positive values? – Algirdas Preidžius Aug 14 '18 at 14:11
  • 2
    You should check if `cin >> b;` fails. – Eljay Aug 14 '18 at 14:17
  • It's also entertaining, btw, when the `int` is negative (especially a near-zero negative number), against a properly read `unsigned int`. The promotions may surprise you. – WhozCraig Aug 14 '18 at 14:23
  • @Eljay, good advice, but if you interpret the bits of 4294967291 as a 32-bit signed int, you get -5. Coincidence? or did the `>>` operator succeed (for some definition of "succeed.") – Solomon Slow Aug 14 '18 at 14:23
  • It never fails. I ran it and that was the output. – Kenneth Ligutom Aug 14 '18 at 14:24
  • @SomeWindowsUser That's pointless, and incurs a runtime cost. – George Aug 14 '18 at 14:24
  • @jameslarge • implementation dependent partially succeeded, but actually failed. GIGO when ignoring failure checking, unless one has reason to believe the data is valid (but in this case, we know /a priori/ that we're throwing bad data at the input). – Eljay Aug 14 '18 at 14:55
  • @lubgr, it is not a duplicate and it will never be since I did not understand integer security. I only understand basic C++ programming and never delved into bits of code since it wasn't taught. – Kenneth Ligutom Aug 15 '18 at 12:42

1 Answers1

3

Conversion from signed to unsigned integer is done by the following rule (§[conv.integral]):

  1. A prvalue of an integer type can be converted to a prvalue of another integer type.
    [...]
  2. If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

In your case, unsigned is apparently a 32-bit type, so -5 is being reduced modulo 232. So 232 = 4,294,967,296 and 4,294,967,296 - 5 = 4,294,967,291.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111