Mateusz_madi said:
char c= -1;
int x;
x=c;
printf("%d", x);
Result:
-1
Why it is -1? How -1 is represented in char in binary format?
Caution: The following provides, to quote John Hodgman's book title,
More Information Than You Require.
It printed -1 because you assigned -1 to c, then assigned the value
of c to x, then printed the value of x. I'm surprised that you
find this surprising.
Another interesting question is why it *wouldn't* be -1.
The type "char" (I'll call it "plain char") can be either signed
or unsigned. Either it has the same representation as signed char,
or it has the same representation as unsigned char -- though they're
still three distinct types.
Apparently plain char is signed in your implementation (which is
very common but not universal).
If plain char were an unsigned type, then the initialization
would convert the value -1 from int to char. The rules of
signed-to-unsigned conversion are such that the result is CHAR_MAX-1,
and if plain char is a signed type, then CHAR_MAX-1 is likely to
be 255.
The assignment ``x=c'' then converts the value 255 from char to int.
Since int can (probably) represent the entire range of char, the
conversion yields the same value in the new type, so x gets the
value 255, which is then printed. You can see what would happen
by modifying your program so c is declared as unsigned char rather
than char.
You'll note that several of my statements were qualified with
"likely" or "probably". The number of bits in a char (i.e., in
a byte) is the value of CHAR_BIT, which is defined in <limits.h>
The standard requires CHAR_BIT to be at least 8, but it can legally
be larger.
And if CHAR_BIT is at least 16, then it's possible that int is only
as wide as char. In that case, if plain char is an unsigned type,
then (signed) int can't represent all its values, which affects
the rules for converting from char to int.
You're not likely to run into any systems like this (I never have),
though I understand that DSPs (Digital Signal Processors) commonly
have CHAR_BIT set to 16 or 32.
As for how -1 is represented in char in binary format, there's
probably no good reason for you to care. C's conversion rules
are defined in terms of values, not representations. But on any
system you're likely to encounter, storing -1 in a char (which will
store -1 if char is signed, or CHAR_MAX, probably 255, if char is
unsigned) will *probably* set all the bits to 1. (There are other
possible represntations for signed integers, namely 2's-complement
and 1s'-complement, but few if any modern systems use them.)
And if you got this far without falling asleep, I'm impressed.
}