1

I have to write a program to create overflow and underflow for int-type variables and output the value of the variable in decimal and hex when overflow or underflow occurs.

So here is my code:

#include <stdio.h>
#include <limits.h>

int main() {


   int delta = INT_MAX;
   printf("\n delta = %d (%4x)", delta, delta);
   delta = delta + 1;
   printf("\n delta +1 = %d (%4x)", delta, delta);
   delta = delta +2;
   printf("\n delta +2 = %d (%4x)", delta, delta);

   printf("\n");

   int delta_min = INT_MIN;
   printf("\n delta_min = %d (%4x)", delta_min, delta_min);
   delta_min = delta_min - 1;
   printf("\n delta_min -1 = %d (%4x)", delta_min, delta_min);
   delta_min = delta_min -2;
   printf("\n delta_min -2 = %d (%4x) \n\n", delta_min, delta_min);

return 0;
}

The answer is supposed to be like

delta         = 2147483647   (7fffffff)
delta +1      = -2147483648  (80000000)
delta + 2     = -2147483647  (80000001)

delta_min     = -2147483648  (80000000)
delta_min -1  = 2147483647   (7fffffff)
delta_min -2  = 2147483646   (7ffffffe)

But my answer is coming out like

delta         = 2147483647   (7fffffff)
delta +1      = -2147483648  (80000000)
delta + 2     = -2147483646  (80000002)    <<

delta_min     = -2147483648  (80000000)
delta_min -1  = 2147483647   (7fffffff)
delta_min -2  = 2147483645   (7ffffffd)    <<

I cannot figure out what am I doing wrong here. I'm not asking you to solve my homework. Just a hint would be extremely helpful!

Thank you for taking your time to read it~

2 Answers2

0

It looks like you are unsure about why it is adding 3 instead of adding 2.

delta + 2     = -2147483646  (80000002)    <<

It's because you reassigned your delta variable instead of storing the result in a separate variable.

delta = delta + 1 // delta is reassigned to -2147483648
// delta + 1     = -2147483648  (80000000)
delta = delta + 2 // Here is the problem. It should be delta + 1.
// delta + 2     = -2147483646  (80000002)    <<

Instead, you should just add 1 each time.

the_storyteller
  • 2,335
  • 1
  • 26
  • 37
0

Keeping all the good comments about undefined behavior being undefined, for the sake of the exercise, the results you are getting "make sense". You start out at INT_MAX:

int delta_min = INT_MAX;

delta         = 2147483647   (7fffffff)

add one, and get you overflow :

delta = delta + 1;

delta +1      = -2147483648  (80000000)

You then add two, and the value you get is now two greater :

delta = delta +2;

delta + 2     = -2147483646  (80000002)    <<

The output seems "correct" to me. The final value you are getting is actually delta_min + 3. There are a couple easy ways you could solve this, which I am sure you will be able to figure out.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31