Pattern 21Automatic Type Promotion


This pattern describes how to automatically and safely promote arithmetic operand types.


The goal of automatic type promotion is to get all operands of a single operation to be of the same type or compatible types. That’s just how computer CPU instructions want their operands. Unfortunately, that’s fairly inconvenient from a programming point of view. We often want to use a variety of types within the same operation such as 3+’0’. Most programming languages would, for example, interpret 3+’0’ as 3+(int)’0’.

A language application can convert between types at will as long as it doesn’t lose information. For example, we can convert 4 to 4.0 but can’t convert 4.5 to integer 4 without losing information. ...

Get Language Implementation Patterns now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.