Possible Duplicate:
Best way to detect integer overflow in C/C++
I'm a beginner to C programming and I wrote a program to read long int
byte at a time and print out at the end of a whitespace. I need to configure it to catch overflow/underflow using LONG_MAX
and LONG_MIN
in limits.h
library. I'm not allowed to cast up to anything higher than long int
, and also it should detect overflow for negative numbers too. Here's my code:
int main(void)
{
int c;
int state;
long int num = 0;
while((c = getchar()) != EOF)
{
switch(state)
{
case 0:
{
if (isspace(c))
{
//do nothing;
}
else
{
state = 1;
num = 10 * num + (c - '0');
}
break;
}
case 1:
{
if (isspace(c))
{
printf("%ld\n", num);
num = 0;
state = 0;
break;
}
num = 10 * num + (c - '0');
if (num < LONG_MIN || num > LONG_MAX)
{
printf("overflow\n");
break;
}
break;
}
}
}
return 0;
}
The part where if (num < LONG_MIN || num > LONG_MAX)
doesn't seem to work because, for example, if the input is LONG_MAX
+1, it overflows and become LONG_MIN
and vice versa when underflows.