Reputation: 151
What can a person do to find out how their system responds to an overflow condition? Describe a way a person can test how their system responds to an underflow condition.
I do understand what an overflow and an underflow is, I looked this up on wikipedia, but I do not understand how it can be tested from system to system.
Upvotes: 3
Views: 5664
Reputation: 11428
For integer numbers, encoded in 2-complement, there's a way to detect overflow after an addition operation: check the signs of both operands and result. If operands have the same sign but result hasn't, there was an overflow.
int is_overflow (char a, char b, char res)
{
char mask = (1<<(8*sizeof(char)-1));
if ((a & mask) == (b & mask) && (a & mask) != (res & mask))
return 1;
else
return 0;
}
For example:
char a = 127;
char b = 1;
char c = a + b;
is_overflow (a, b, c) => 1
char a = -128;
char b = -1;
char c = a + b;
is_overflow (a, b, c) => 1
char a = -1;
char b = 1;
char c = a + b;
is_overflow (a, b, c) => 0
char a = 1;
char b = 1;
char c = a + b;
is_overflow (a, b, c) => 0
For underflow, the thing is different. I don't know about integer underflow, but floating point underflow. For these situations, the numeric processor has flags to test whether the last operation underflowed, but I don't know of a portable way to test those flags from C.
Upvotes: 1
Reputation: 8861
With unsigned
integers, C requires underflow and overflow to behave in a certain manner. For example, consider the following:
unsigned int uintUnderflow = 0;
unsigned int uintOverflow = UINT_MAX;
printf("%u\n", --uintUnderflow); // Guaranteed to be UINT_MAX
printf("%u\n", ++uintOverflow); // Guaranteed to be 0
Now with signed
integers, implementations may define underflow and overflow however they wish. That is the nature of undefined behavior. If you can't find documentation on how it will behave you'll have to experiment with it yourself:
int intUnderflow = INT_MIN;
int intOverflow = INT_MAX;
printf("%d\n", --intUnderflow); // Implementation defined
printf("%d\n", ++intOverflow); // Implementation defined
Upvotes: 2
Reputation: 15501
You could try something like this:
#include <stdio.h>
#include <limits.h>
int main() {
int n = INT_MAX;
++n;
printf("INT_MAX + 1: %d\n", n);
unsigned u = UINT_MAX;
++u;
printf("UINT_MAX + 1: %u\n", u);
n = INT_MIN;
--n;
printf("INT_MIN - 1: %d\n", n);
u = 0;
--u;
printf("0u - 1: %u\n", u);
return 0;
}
Upvotes: 0
Reputation: 50190
assuming you mean c. Something like
int main()
{
int i = 0;
while(1)
{
i++;
}
}
light fuse and stand well back
Upvotes: 1