In C and C ++, you should always pay attention to numerical overflow, because the assumption of the language is that the programmer will never make such an error.
A char is a kind of integer and often 8 bits and signed, which gives an acceptable range of -128 ... 127. This means that when storing a value in a char variable, you should never exceed these limits.
char also a "storage type" meaning that calculations are never performed using char and, for example,
char a = 'z';
x will actually get the value 142, because the calculation is not "overflowing" (all char values ββare first converted to integers in the expression)
However, storing the value is greater than the allowable range in the variable undefined behavior and code, for example
char a = 'z';
unacceptable: the calculation is fine, but the result does not fit into x .
Storing a value outside the acceptable range for signed characters in a signed char variable is exactly what your code did and what caused the strange observable behavior. A simple solution is to use an integer to store intermediate results instead of char.
A few more notes:
- Several character functions do handle integers because they must be able to handle the special
EOF value in addition to all valid characters. For example, fgetc returns int and isspace accepts int (they return / accept either char code converted to unsigned or EOF ). char can be signed or not depending on the compiler / options; if unsigned and 8-bit wide, the valid range is 0 ... 255- Most often, when you save the value of the external boundaries in a variable, you simply get a βwrappingβ of behavior, but this is not guaranteed and does not always happen. For example, the compiler is allowed to optimize
(char(x + 20) < char(y + 20)) to (x < y) , since the assumption is that the programmer will never overflow with signed numerical values.
source share