The compiler deals with the source code as a string, so in C ++, for example, when it supports a type operator unsigned char x = 150;, it knows from type restrictions that it unsigned charmust be in the range between 0and 255.
My question is that the number 150remains a string, which compiler algorithm does it use to compare a sequence of digits - 150in this case - against type restrictions?
I made a simple algorithm to do this for type 'int' for decimal, octal, hexadecimal and low-value binary code, but I don't think the compiler does such a thing to detect overflow in numbers.
the made algorithm is encoded in C ++:
typedef signed char int8;
typedef signed int int32;
#define DEC 0
#define HEX 1
#define OCT 2
#define BIN 3
bool isOverflow(const char* value, int32 base)
{
static const char* max_numbers[4][2] =
{
{ "2147483647", "2147483648" },
{ "7fffffff", "80000000" },
{ "17777777777", "20000000000" },
{ "01111111111111111111111111111111", "10000000000000000000000000000000" }
};
static const int32 number_sizes[] = { 10, 8, 11, 32 };
int32 str_len = strlen(value);
int32 signExist = ((base == DEC || base == OCT) && *value == '-');
int32 non_zero_index = signExist;
while(non_zero_index < str_len && value[non_zero_index] == 0) non_zero_index++;
if (non_zero_index == str_len) return false;
int32 diff = str_len - non_zero_index;
if (diff < number_sizes[base]) return false;
if (diff > number_sizes[base]) return true;
int8 left1 = 0, left2 = 0;
for (int32 i = 0; non_zero_index < str_len; non_zero_index++, i++)
{
left1 = value[non_zero_index];
left2 = max_numbers[signExist][i];
if (left1 != left2) return left1 > left2;
}
return false;
}
, float- IEEE.
, , , ?