Hello,
Am I correct that C automatically typecasts from int to char in the following?
or do I have to explicitly do ...Code:int c = 97; char b; b = c;
thanksCode:int c = 97; char b; b = (char) c;
Hello,
Am I correct that C automatically typecasts from int to char in the following?
or do I have to explicitly do ...Code:int c = 97; char b; b = c;
thanksCode:int c = 97; char b; b = (char) c;
Yes. It will store the lowest sizeof(char) bytes (1 in this case) into b including a sign bit if it is signed. In this case, since b is a signed char, it will also perserve its sign.
It depends on the compiler's settings... It can be unsigned as well.since b is a signed char
Yes, but some compilers on the high warning levels can show a warning about "possible loss of data"that C automatically typecasts from int to char
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
So I should explicitly assign it like this?
or like this if I wanted to make sure it was unsigned?Code:b = (char) c;
thanksCode:b = (unsigned char) c;
No, no no, Some compilers specify 'char' as 'unsigned char', this is unusual because most data-types are signed by default.
so to ensure C is unsigned,
Code:unsigned char c; int b; /* signed by default */ b = (unsigned char) c; /* To silence the high level warnings. */
Last edited by zacs7; 05-14-2007 at 03:14 AM.