Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Created January 28, 2018 14:45
Show Gist options
  • Save pervognsen/6c4a5ca77b99115989510f2beb01cc76 to your computer and use it in GitHub Desktop.
Save pervognsen/6c4a5ca77b99115989510f2beb01cc76 to your computer and use it in GitHub Desktop.
int parse_int(const char *str, bool *overflow) {
int pos = 1;
if (*str == '-') {
pos = 0;
str++;
}
int num = 0;
*overflow = false;
while (isdigit(*str)) {
int d = *str - '0';
if (num < (INT_MIN + d) / 10) {
*overflow = true;
num = INT_MIN;
break;
}
num = 10 * num - d;
*str++;
}
if (pos) {
if (num < -INT_MAX) {
*overflow = true;
num = INT_MAX;
} else {
num = -num;
}
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment