Example 1 — Detect an out-of-range conversion
strtol sets errno to ERANGE for numbers that do not fit in a long.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
errno = 0;
long v = strtol("99999999999999999999", NULL, 10);
if (errno == ERANGE) {
printf("out of range (ERANGE)\n");
} else {
printf("value = %ld\n", v);
}
return 0;
} How It Works
errno = 0clears any earlier error.- The 20-digit value exceeds
LONG_MAX, sostrtolreturnsLONG_MAXand setsERANGE. - Use
perrorwhen you want the message printed tostderr.
