3.2. Casting

Casting is the operation of changing the type of a value. This can be necessary for a number of reasons: when assigning a larger value to a smaller one, say a WORD to a BYTE, the compiler will issue a warning. An explicit cast will eliminate that warning:


        VAR WORD xx
        VAR BYTE yy
        ;
        ; the following assignment will issue:
        ; warning: assignment to smaller type; truncation possible
        ;
        yy = xx
        ;
        ; no warning will be generated below
        ;
        yy = BYTE(xx)
      
In the first case, the compiler wants you to know there might be an issue (a rather common one). In the second case, you've explicitly told the compiler you know these types are different, but that is OK.

Another case where casting is necessary is to guarantee correct promotion during an operation. Take the following:


        VAR WORD xx
        VAR BYTE yy
        ;
        ; this is not likely to do what you expect
        ;
        xx = yy * yy
        ;
        ; this will generate the correct result
        ;
        xx = WORD(yy) * WORD(yy)
      
Remember that an operator only sees its two operands, it has no other context. Say the value of yy is 255. In the first case xx will be assigned a value of 1: the lower eight bits of the result. In the second case, the value of yy is promoted to a WORD, so xx will be assigned 65025 which is more likely what you would expect.