code_junkie

Why don't languages raise errors on integer overflow by default?

Nov 11th, 2011
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. //Returns the sum of the values in the specified list.
  2. private static int sumList(List<int> list)
  3. {
  4. int sum = 0;
  5. foreach (int listItem in list)
  6. {
  7. sum += listItem;
  8. }
  9. return sum;
  10. }
  11.  
  12. List<int> list = new List<int>();
  13. list.Add(2000000000);
  14. list.Add(2000000000);
  15. int sum = sumList(list);
  16.  
  17. int main()
  18. {
  19. uint32_t shipsHeadingInDegrees= 0;
  20.  
  21. // Rotate by a bunch of degrees
  22. shipsHeadingInDegrees+= 0x80000000; // 180 degrees
  23. shipsHeadingInDegrees+= 0x80000000; // another 180 degrees, overflows
  24. shipsHeadingInDegrees+= 0x80000000; // another 180 degrees
  25.  
  26. // Ships heading now will be 180 degrees
  27. cout << "Ships Heading Is" << (double(shipsHeadingInDegrees) / double(0xffffffff)) * 360.0 << std::endl;
  28.  
  29. }
Add Comment
Please, Sign In to add comment