Skip to content

Instantly share code, notes, and snippets.

@scottopell
Created April 29, 2014 16:37
Show Gist options
  • Save scottopell/11405604 to your computer and use it in GitHub Desktop.
Save scottopell/11405604 to your computer and use it in GitHub Desktop.
// The function is supposed to return false when
// x+y overflows unsigned short.
// Does the function do it correctly?
bool IsValidAddition( unsigned short x,
unsigned short y) {
if (x+y < x)
return false;
return true;
}
@scottopell
Copy link
Author

During arithmetic operations, the C99 standard states that "if an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int."

Therefore this will never work to check for overflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment