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;
This is a discussion on a couple questions about typecast within the C Programming forums, part of the General Programming Boards category; Hello, Am I correct that C automatically typecasts from int to char in the following? Code: int c = 97; ...
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
If I have eight hours for cutting wood, I spend six sharpening my axe.
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.