What is often applied to the char type in C + + also uses the char type as a looping condition for the loop statement, but often it is most prone to errors, overflow, and a dead loop. Here we will briefly explain why this is happening.
First, understand the range of values for the following char types:
Char is divided into unsigned (unsigned) and signed (signed) two types:
Unsigned (unsigned) range of values: 0~255;
The value range for signed (signed) is: -128~127.
Generally we often use char to declare a variable, the compiler is signed by default, that is, the range is: -128~127.
Common overflow issues:
Knowing the range of values for a char type makes it easy to understand why overflow occurs. There is a lot of overflow where a variable of type char is used as the conditional part of a loop statement, so it is easy to overflow, and here is a brief explanation of the char type's self-increment.
Generally, as a cyclic condition, the char type is often assigned an int type, such as char i = 0, and then I is self-increasing.
When I is unsigned, the value range is 128 ~ 127, when the i=127 after the self-increment, then I is not equal to 128, but equal to 128; When i=-128, then the self-reduction is not equal to 129, but equal to 127.
When I is a signed type, the value range is 0 ~ 255, when i = 255, then the self-increment, then i=0, instead of equal to 256, when i=0, the self-reduction i= 255, instead of 1.
this is because the char type is the same for the signed, first 24 digits and the last 8th bit, and for unsigned, the first 24 bits are always zero.
Causes of the above results:
When signed, when i = 127, the binary is: 0 .... 0 0111 1111, then add 1 after, according to the above principle, changed to: 1 .... 1 1000 0000, result i =-128; When i=-128, minus 1, binary becomes: 0 .... 0 0111 1111, result i = 127.
When unsigned, when i=255, the binary is: 0 .... 0 1111 1111, plus 1, according to the above principle, changed to: 0 .... 0 0000 0000, the result is i= 0; When i = 0 o'clock, minus 1, the binary is: 0 ... 0 1111 1111, the result is 255.
This is illustrated by an example:
#define S8 charstatic int k = 0;void func () { S8 i = 0; for (i = 0; i < i++) { k + = i&3; } printf ("k =%d\n", k);}
Many people here may be able to write on the calculation, calculated k= 192, but the result is wrong.
Reason: Note I is a char type, and is signed, and is assigned the initial value 0, here when i = 127, the program will be normal, and then I self-increment, to 128, and finally satisfy the condition, the program does not terminate, so there is a char type overflow, the program enters the dead loop. At this point, either change the conditions in the loop, instead: I < 127, or change the type of I to int.
Overflow problem with char types in C + +