0

I accidentally discovered this today. Is this supposed to happen? Is this something we should all be warned about?

Since this is an unsigned integer, shouldn't I have gotten an error?

uint foo = 10;
foo = foo - 35;
Console.WriteLine(foo);

Output: 4294967271

Scott Jore
  • 71
  • 8
  • 1
    uint means _unsigned int_ – Steve Jun 06 '16 at 13:11
  • I was expecting to get an error - shouldn't I have gotten an error? – Scott Jore Jun 06 '16 at 13:11
  • 4
    `Is this something we should all be warned about?` It should be understood that by default, C# uses an unchecked context. That allows wrapping like this to happen. If you want an error/warning, change your project configuration to use a checked context by default, or use the `checked` keyword. – Glorin Oakenfoot Jun 06 '16 at 13:12
  • 5
    Yes, you should be warned about it. Don't hesitate to enable that warning. Project > Properties > Build tab > Advanced button > tick the "Check for arithmetic overflow/underflow" checkbox. – Hans Passant Jun 06 '16 at 13:17
  • When asking a question about something that you don't expect to happen, tell what you do expect to happen in your question. Also, show your research. And no, the last thing to point at should generally be your code, not the language or framework you're using, so I removed the ".NET BUG?" from your title if you don't mind. – CodeCaster Jun 06 '16 at 13:20
  • Is there a best practices reasoning for why the "Check for arithmetic overflow/underflow" checkbox is not ticked by default? Is there any good reason not to check it? Usually, I am pretty good about data validation... granting that we all make mistakes sometimes. – Scott Jore Jun 06 '16 at 13:21
  • @Scott please try searching. See [Why doesn't C# use arithmetic overflow checking by default?](http://stackoverflow.com/questions/13259408/why-doesnt-c-sharp-use-arithmetic-overflow-checking-by-default) and [Why don't languages raise errors on integer overflow by default?](http://stackoverflow.com/questions/103654/why-dont-languages-raise-errors-on-integer-overflow-by-default). – CodeCaster Jun 06 '16 at 13:22
  • I did search for an answer before posting, I didn't find one, I'm guessing that's because I searched for uint instead of integer – Scott Jore Jun 06 '16 at 13:25

1 Answers1

3

you have an arthmetic overflow just enable Buid-Advanced-Check for arithmetic... that and you will get this exception:

An unhandled exception of type 'System.OverflowException' occurred in Additional information: Arithmetic operation resulted in an overflow.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70