Type conversion in expressions

Top  Previous  Next

In the Type Conversion we already explained what happens when you assign the value of a variable of one type to a variable of another type. This section deals the cases where variables of different types are used in expression. For example, if x is byte and i is integer, what will happen when you do "x+i"?

The Virtual Machine operates on 16-bit values by default

Native data width for the Virtual Machine is 16 bits. When you are performing calculations on 8-bit and/or 16-bit variables, result is always truncated to 16 bits. Also, all intermediary calculations are done using 16-bit arithmetic. Consider the following example first:

 

 

dim x,y,z as byte

x=150

y=200

z=(x+y)/10 ' result of 35 is within byte variable's range, but intermidiary calculations require 16-bit ariphmetic.

 

 

The above example will give correct result. Even though all three variables are of byte type, internal calculations are 16-bit, so when x+y produces 350, which is beyond the range of the byte variable, the Virtual Machine handles this in the right way. Now, let's see another example:

 

 

dim i,j,k as word

i=50000

j=60000

k=(i+j)/10 ' result will be 4446, which is incorrect. 32-bit ariphmetic was not automatically used!

 

 

This example requires 32-bit calculations because i+j will produce a number which is outside the scope of 16-bit calculations. However, our compiler will not invoke 32-bit calculations automatically. Read on, this is not all...

Mixing in a 32-variable will cause the compiler to use 32-bit calculations

For the example above, turn i or j into a dword. Now, your calculations will be correct. Mixing in any 32-bit variable will aotumatically upgrade calculations to 32 bits!

 

 

dim i,k as word

dim d as dword

i=50000

d=60000

k=(i+d)/10 ' result will be 11000. This is correct!

String and non-string variables cannot be mixed!

Yes, sorry, but you cannot do the following (compiler will generate type mismatch error):

 

 

'Wrong!!!

dim x as byte

x=5+"6"

 

 

In case you are wondering why x="6" would work but x=5+"6" doesn't: the latter is a mixed expression in which the compiler cannot decide what is implied: conversion of string to value and then addition, or conversion of value to string and then string concatenation!