Overflow
We usually, see this warning in C and C++ when data type overflow happen
In C we have basic data types such as int, float, and char but each data type will have a different range
For example, the range for char is from -128 to +127
Suppose, if you assign a char variable with 130[exceeded the normal range of char-128 to +127] then, in that case, it will take a cyclic value[which is 44] and that is known as overflow
#include <iostream>
using namespace std;
int main()
{
char a=300;//warning:overflow in implicit constant conversion
cout << (int)a<< endl;//Type_casting char a to int a
return 0;
}
Output
44
But, Why you got this warning?
Because you have exceeded the normal range of a data type
But, how to avoid this warning
in short, by being in the range of the data type and not exceeding the normal data type range which you have declared
At the same time, always keep in mind that a char variables are just a single character enclosed within single quotes
Such as
letters ‘a’,’b’
in addition, you can also assign char to numerical values without a single quote but should be in the range of -128 to 127
Does this warning have any effect on the output of the program?
of course, yes!
Of course, it will alter the accuracy of the result
But, how?
Let’s see an example
for instance, suppose, you have a variable of type char
So, what is the maximum value you can store in char
in general, the answer is +127
in reality, can we store +128 in char?
No!
But, why?
Because the compiler will throw a warning indicating that you exceeded the normal range of char
until now, okay,
Here’s another one
at this time, suppose you have a variable of char type and you store the value +130 in it
that is, Char x=+130;
At this instant, print the variable x
At this point, you get a result as -126 which is wrong
It should be +130 but because of this over this overflow the result gets altered and corrupted
to sum up, here are some standard data types range that you should not exceed to avoid warning
standard data types range
Data type | range |
char | -128 to 127 |
unsigned char | 0 to 255 |
signed char | -128 to 127 |
int | -32768 to 32767 |
unsigned int | 0 to 65535 |
signed int | -32768 to 32767 |
short int | -32768 to 32767 |
unsigned short int | 0 to 65535 |
signed short int | -32768 to 32767 |
long int | -2147483648 to 2147483647 |
unsigned long int | 0 to 4294967295 |
signed long int | -2147483648 to 2147483647 |
float | 3.4E-38 to 3.4E+38 |
double | 1.7E-308 to 1.7E+308 |
long double | 3.4E-4932 to 1.1E+4932 |
Sizes of data types may vary from one compiler to another
Compiler | Short | Int | Long |
16-bit(turbo C/C++) | 2 | 2 | 4 |
32-bit(Visual studio, gcc) | 2 | 4 | 4 |
A 2-byte integer can take values from -32768 to +32767
A 4-byte integer can take values from -2147483648 to +2147483647
Leave a Reply