17.02.2015 Views

CCS C Compiler Manual PCB / PCM / PCH

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

COMMON QUESTIONS & ANSWERS<br />

How are type conversions handled?<br />

The compiler provides automatic type conversions when an assignment is performed. Some<br />

information may be lost if the destination can not properly represent the source. For example:<br />

int8var = int16var; Causes the top byte of int16var to be lost.<br />

Assigning a smaller signed expression to a larger signed variable will result in the sign being<br />

maintained. For example, a signed 8 bit int that is -1 when assigned to a 16 bit signed variable<br />

is still -1.<br />

Signed numbers that are negative when assigned to a unsigned number will cause the 2's<br />

complement value to be assigned. For example, assigning -1 to a int8 will result in the int8 being<br />

255. In this case the sign bit is not extended (conversion to unsigned is done before conversion<br />

to more bits). This means the -1 assigned to a 16 bit unsigned is still 255.<br />

Likewise assigning a large unsigned number to a signed variable of the same size or smaller will<br />

result in the value being distorted. For example, assigning 255 to a signed int8 will result in -1.<br />

The above assignment rules also apply to parameters passed to functions.<br />

When a binary operator has operands of differing types then the lower order operand is<br />

converted (using the above rules) to the higher. The order is as follows:<br />

Float<br />

Signed 32 bit<br />

Unsigned 32 bit<br />

Signed 16 bit<br />

Unsigned 16 bit<br />

Signed 8 bit<br />

Unsigned 8 bit<br />

1 bit<br />

The result is then the same as the operands. Each operator in an expression is evaluated<br />

independently. For example:<br />

i32 = i16 - (i8 + i8)<br />

The + operator is 8 bit, the result is converted to 16 bit after the addition and the - is 16 bit, that<br />

result is converted to 32 bit and the assignment is done. Note that if i8 is 200 and i16 is 400<br />

then the result in i32 is 256. (200 plus 200 is 144 with a 8 bit +)<br />

Explicit conversion may be done at any point with (type) inserted before the expression to be<br />

converted. For example in the above the perhaps desired effect may be achieved by doing:<br />

i32 = i16 - ((long)i8 + i8)<br />

353

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!