Introduction
Overflow means you are carrying out an operation such that the value either exceeds the maximum value or is less than the minimum value of the data type.
Program
// the program gives maximum and minimum values of data type
#includemain() { char i,j ; i = 1;
while (i > 0) // A { j = i; // B i++; // C } printf
("the maximum value of char is %d\n",j); printf
("the value of char after overflow is %d\n",i); }
Explanation
-
This program is used to calculate the maximum positive value of char data type and the result of an operation that tries to exceed the maximum positive value.
-
The while loop is terminated when the value of i is negative, as given in statement A. This is because if you try to add 1 to the maximum value you get a negative value, as explained previously (127 + 1 gives −128).
-
The variable j stores the previous value of i as given in statement B.
-
The program determines the maximum value as 127. The value after overflow is -128.
-
The initial value of i is 1 and it is incremented by 1 in the while loop. After i reaches 127, the next value is -128 and the loop is terminated.
Points to Remember
-
In the case of signed char, if you continue adding 1 then you will get the maximum value, and if you add 1 to the maximum value then you will get the most negative value.
-
You can try this program for short and int, but be careful when you are using int. If the implementation is 4 bytes it will take too much time to terminate the while loop.
-
You can try this program for unsigned char. Here you will get the maximum value, 255. The value after overflow is 0.
No comments:
Post a Comment