Type conversion is a frequently asked concept in any software/firmware interview.
Rules
Rules
- assignment: right type converts to left type, with or without sign expression
- compare & binary operator: converts low to high (unsigned higher than signed)
Char to Int
char c = 0xFF;
int i = c;
cout << i;
It's machine dependent. There are two situations. (without sign extension)
1) It's always converted to a positive number.
1) It's always converted to a positive number.
255
2) It can be both positive or negative number, and depend on MSB of c. (with sign extension)
-1
c = 0xFF = -1 —-> i = -1 = 0xFFFF
Int to Char
directly truncate
Pointer Conversion
int i = 10;
char *c;
c = &i;
-> convert pointer of int to pointer of char
-> i + 1 = i + sizeof(int)
-> c + 1 = c + sizeof(char)
char *c;
c = &i;
-> convert pointer of int to pointer of char
-> i + 1 = i + sizeof(int)
-> c + 1 = c + sizeof(char)
沒有留言:
張貼留言