0

I am taking a Microsoft Course called Introduction to C++ on edx.org. It's a good course. Instead of just breezing through, I am trying to understand as much as possible. Below is the part of this video that I do not understand. I don't understand why unsigned int u{ 0 }; outputs 0, but when I change it to u = -2;, it outputs 4294967294.

    #include <iostream>

    int main()
    {

    unsigned int u{ 0 };
    std::cout << u << std::endl;
    u = -2; 
    std::cout << u << std::endl; // prints 4294967294 as u?

    return 0;
    }

Thank you for your time in advance.

host_255
  • 361
  • 2
  • 7
  • 18
  • 1
    TL;DR: It's `UINT_MAX + 1 + (-2)`. – melpomene Jan 03 '17 at 06:32
  • @melpomene @jesper-juhl You both tried to insult me with TL;DR and Hint, but you did not answer the question, which is incredible. `UINT_MAX` is `4294967295`. How did `u` subtract `1` from `UINT_MAX` when `unsigned int u{ 0 };` outputs `0`, and the next line is `u = -2;`, which is saying that `u`, which is currently `0`, is now assigned the value of `-2`, but is instead outputting `4294967294`. Why does `unsigned` do this? I have researched `unsigned` on cppreference.com, and read over that "duplicate", which still fails to explain it. So, please stop trying to look cool and answer this. – host_255 Jan 03 '17 at 09:52
  • I did not try to insult you, you walnut. My comment was intended as a summary of the duplicate link. I don't know why you're talking about subtracting `1`; no one has claimed it would do that. The duplicate explains exactly what's going on. If you don't understand it, ask a specific question. "*How did `u` subtract `1`*" is a bad question because it's wrong. No one's subtracting 1. – melpomene Jan 03 '17 at 10:31
  • You also said "*you did not answer the question, which is incredible*". Well... you did not actually ask a question. Re-read your original post; there's nothing to answer there. – melpomene Jan 03 '17 at 10:39
  • @melpomene I asked "prints 4294967294 as u?" – host_255 Jan 04 '17 at 06:36
  • @melpomene I almost don't care anymore. I saw some answer about how it adds one before it subtracts 2, so I'll just take that as the answer and be okay with how superficial it is. Maybe I will get the answer as to why that happens later. Cheers, mate. – host_255 Jan 04 '17 at 06:40
  • Because (as explained in the linked answer) all unsigned integer arithmetic is done modulo (max + 1). Or do you want to know why C(++) was designed to work this way? – melpomene Jan 04 '17 at 09:56
  • No, you did not ask that, but the answer is "yes". – melpomene Jan 04 '17 at 09:56

0 Answers0