Created
January 28, 2018 14:45
-
-
Save pervognsen/6c4a5ca77b99115989510f2beb01cc76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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