#include <stdio.h>
#include <stdlib.h>
int main()
{
signed char chr=128;
printf("%d\n",chr);
return 0;
}
Asked
Active
Viewed 400 times
-5
-
5`128` is out of the range of an 8-bit `signed char`. What result did you expect? – Weather Vane Jan 14 '22 at 16:13
-
@WeatherVane Please give some more light on the explaination. Thanks. – AyushDwi Jan 14 '22 at 16:15
1 Answers
2
Do you know about integer limits? A char
value takes up 1 byte. A byte is usually 8 bits. To calculate the limit through the number of bits, the calculation is 2^n-1
meaning an integer with 8 bits has a range from 0 to 255 when unsigned. Since your variable is signed, it allocates a bit to the sign, meaning it has a range from -128 to 127. Since you assigned it as 128, it overflowed, rolling back over to -128. If your program doesn't use negative numbers, you should use signed char
, otherwise you might want to use a short
which is 2 bytes.

NY can
- 56
- 1
- 5
-
-
The C standard does not fix the number of bits in a byte. It must be at least eight but may be larger. – Eric Postpischil Jan 14 '22 at 16:18
-
2When addressing integer “overflows,” care should be taken with C semantics. This is not an overflow as the C standard defines it, and the standard does not require “rolling back over.” Conversion of out-of-range integer values to signed integer types is implementation-defined. The implementation may define it to wrap, to clamp, to trap, or to do other things. – Eric Postpischil Jan 14 '22 at 16:19
-
@EricPostpischil the error however seems to be an 8 bits byte overflow. There might be embedded processors and mini/mainframes with more than 8 bits per "byte," can you mention one? (interested) – Joop Eggen Jan 14 '22 at 16:29
-
1@JoopEggen Do you mean like [those ones](https://stackoverflow.com/questions/32091992/is-char-bit-ever-8)? – Bob__ Jan 14 '22 at 16:33
-
1Re "*A `char` value takes up 1 byte.*", Yes. /// Re "*A byte is 8 bits*", Usually, but not always. They have been known to be as large as 32 bits, and as odd as 9 bits. That said, it is 8 bits in the OP's case. /// Re "*Since your variable is signed, it has a range from -128 to 127.*", Or -127 to 127 on some systems. That said, it's obviously -128 to 127 for the OP. /// Re "*rolling back over to -128.*", That is what happpened, but other implementations may handle it differently. – ikegami Jan 14 '22 at 17:06