String to Integer with Error Checking
Write bool parse_int32(const char *s, int32_t *out) that converts a decimal string to an int32_t.
- Accept an optional leading
+or-. - Reject empty strings, strings with any non-digit characters, and values outside
INT32_MIN..INT32_MAX. - On success write the value to
*outand returntrue; on failure returnfalseand leave*outunchanged.
You would use something like this to parse commands from a UART console.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Accumulate the magnitude as an unsigned 32-bit (or 64-bit) value and check the limit before each multiply-and-add. The negative limit is one larger than the positive one.
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
bool parse_int32(const char *s, int32_t *out)
{
bool neg = false;
uint32_t mag = 0;
if (*s == '+' || *s == '-') neg = (*s++ == '-');
if (*s == '\0') return false;
const uint32_t limit = neg ? 2147483648u : 2147483647u;
for (; *s; s++) {
if (*s < '0' || *s > '9') return false;
uint32_t d = (uint32_t)(*s - '0');
if (mag > (limit - d) / 10u) return false; /* mag*10 + d > limit */
mag = mag * 10u + d;
}
*out = neg ? (int32_t)(0u - mag) : (int32_t)mag;
return true;
}
atoi cannot report errors at all, and signed overflow during accumulation is undefined behaviour, so the magnitude is kept unsigned. The overflow test is rearranged so it never overflows itself. Converting 0u - mag back to int32_t for INT32_MIN relies on two's complement conversion, which is guaranteed in C23 and is how every real compiler behaves.
The standard-library alternative is strtol with errno and endptr checks.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
int32_t v = 7;
CHECK(parse_int32("123", &v) && v == 123);
CHECK(parse_int32("-42", &v) && v == -42);
CHECK(parse_int32("+5", &v) && v == 5);
CHECK(parse_int32("2147483647", &v) && v == INT32_MAX);
CHECK(parse_int32("-2147483648", &v) && v == INT32_MIN);
v = 7;
CHECK(!parse_int32("2147483648", &v) && v == 7);
CHECK(!parse_int32("", &v));
CHECK(!parse_int32("-", &v));
CHECK(!parse_int32("12a", &v));
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}