Type Conversion

Top  Previous  Next

Type conversion happens whenever you assign a variable of one type to a variable of another type.

 

Conversions without loss

This is when you assign the value of one unsigned or signed variable to another variable that can hold this value unchanged.

Example of a loss-less conversion:

 

Tibbo BASIC:

dim i as word=50
dim x as char=i

 

X is "smaller" than i -- it's just one byte against two bytes of i. In addition, x is a signed variable, so it can only hold positive values of up to 127.

Fortunately, the value of i (50) is within this range, so this conversion won't lead to any loss of data.

 

Conversions with loss

Consider this example now:

 

Tibbo C:

unsigned int i=0x5AA5;
unsigned char x=i; //The result is 0xA5

 

With this, x will assume the value of the least significant byte of i (0xA5). The most significant byte of i will be lost.

 

note_further-wtTIDE and TiOS try not to bug you with incessant warnings about (potential) data loss. It is our opinion that some modern languages go to far in trying to hold the user's hand. The result is a dizzying flood of warnings that only distract you. It is your job to know that putting a 16-bit value into an 8-bit one may result in a loss of data.

 

 

Conversions that cause reinterpretation

This is when the receiving variable ends up holding the same binary value with the source variable, but interprets it differently:

 

Tibbo BASIC:

dim i as byte=254
dim x as char=i 'The result is -2

 

In this example x ends up with the same binary value but since x is a signed variable this binary value has a different meaning. 254 becomes -2.

 

Conversions that round the number (remove fractions)

Conversions from a float (real) variable into any other numerical type will cut off the fraction, as real is the only type that can hold fractions.

We do give warnings about this.