How to check out of boundary condition and print a message in C language? For example, let sizeof(int)
=4 bytes, how to check if user input value is more than 2^31
?
Asked
Active
Viewed 828 times
0

perror
- 7,071
- 16
- 58
- 85

Gowtham Siddarth
- 13
- 1
- 2
-
where user input value is a string? If so, what are you using currently to parse the string. Show the code. – weston Aug 02 '15 at 08:38
-
The prgm is get sum of digits of an integer. The input is taken as integer only, but how to put a check if there's an input value beyond the range? – Gowtham Siddarth Aug 02 '15 at 08:58
-
1You need to test the users input before it is placed in an `int` afterwards you can check for between `2^31-2^32`, but they could have entered a larger number. It also depends on the code you are using to convert from users `char*` to `int` so I repeat, show the code!!! – weston Aug 02 '15 at 09:01
-
@user299520 Are you asking how to check if an `int` is outside of the range of an `int`? – melpomene Aug 02 '15 at 09:45
1 Answers
-1
If integer overflow occures then the sum value becomes < 0. Try this code snippet:
void checkOverflow()
{
int sum = 0;
int digits = 10000000000; // one bilion
for (int i = 0; i < 10; i++)
{
sum += digits;
if (sum < 0)
{
printf("Integer overflow - %i", sum);
break;
}
}
}

Denys Kazakov
- 472
- 3
- 17
-
Since when C started having a construct/method called `cout`??? Also, this code won't compile, as you're not returning any int value whereas your function is defined to return an int. – Am_I_Helpful Aug 02 '15 at 09:44
-
Signed integer overflow has undefined behavior. You can't check for it after the fact. – melpomene Aug 02 '15 at 09:47
-
Pardon, I've add the code without compiling it. Corrections added. But in any case you've got the idea. – Denys Kazakov Aug 02 '15 at 09:47
-
Take a look at this answer though http://stackoverflow.com/questions/199333/how-to-detect-integer-overflow-in-c-c. Mine is just an example to show what happens on integer overflow. – Denys Kazakov Aug 02 '15 at 09:49