Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you want an integer overflow to occur?

In this question the topic is how to make VS check for an arithmetic overflow in C# and throw an Exception: C# Overflow not Working? How to enable Overflow Checking?

One of the comments stated something weird and got upvoted much, I hope you can help me out here:

You can also use the checked keyword to wrap a statement or a set of statements so that they are explicitly checked for arithmetic overflow. Setting the project-wide property is a little risky because oftentimes overflow is a fairly reasonable expectation.

I dont know much about hardware but am aware that overflow has to do with the way registers work. I always thought overflow causes undefined behaviour and should be prevented where possible. (in 'normal' projects, not writing malicious code)

Why would you ever expect an overflow to happen and why wouldn't you always prevent it if you have the possibility? (by setting the corresponding compiler option)

like image 940
magnattic Avatar asked Sep 11 '25 07:09

magnattic


1 Answers

The main time when I want overflow is computing hash codes. There, the actual numeric magnitude of the result doesn't matter at all - it's effectively just a bit pattern which I happen to be manipulating with arithmetic operations.

We have checked arithmetic turned on project-wide for Noda Time - I'd rather throw an exception than return incorrect data. I suspect that it's pretty rare for overflows to be desirable... I'll admit I usually leave the default to unchecked arithmetic, just because it's the default. There's the speed penalty as well, of course...

like image 97
Jon Skeet Avatar answered Sep 12 '25 23:09

Jon Skeet