I'm a beginner to C.
This code does what SCHAR_MIN
in <limits.h> do:
#include<stdio.h>
int main(void)
{
printf("Minimum Signed Char %d\n",-(char)((unsigned char) ~0 >> 1) - 1);
return 0;
}
This is what I understood:
(unsigned char)
takes the bits of an unsigned char which is "0000 0000".
~0
gives the complement of it which is "1111 1111" and >> 1
turns the "1" on the left side of "1111 1111" to 0, so it will give "0111 1111". Converting "0111 1111" to integer will give 127 which is the maximum signed char. To get the minimum, we need to invert 127, so we multiply it by -
to get -127 and - 1
gives us -128 which is the minimum. Tell me if I misunderstood something.
Question:
what's the role of (char)
here? Right before ((unsigned char) ~0 >> 1)
? What does it represent?
(char)
is to convert the result of the right expression to a char. This is a cast. By the way, do not considerchar
is always 8 bits! – fpiette- 1
and then try with and without(char)
– Eraklon