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;
Printable View
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.
thanks :)
It depends on the compiler's settings... It can be unsigned as well.Quote:
since b is a signed char
Yes, but some compilers on the high warning levels can show a warning about "possible loss of data"Quote:
that C automatically typecasts from int to char
So I should explicitly assign it like this?
or like this if I wanted to make sure it was unsigned?Code:b = (char) c;
thanks :)Code: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. */
Thanks ... I'm new to typecast :)