Next: , Previous: , Up: Numeric Data Types   [Contents][Index]


4.7 Promotion and Demotion of Data Types

Many operators and functions can work with mixed data types. For example,

uint8 (1) + 1
    ⇒ 2

where the above operator works with an 8-bit integer and a double precision value and returns an 8-bit integer value. Note that the type is demoted to an 8-bit integer, rather than promoted to a double precision value as might be expected. The reason is that if Octave promoted values in expressions like the above with all numerical constants would need to be explicitly cast to the appropriate data type like

uint8 (1) + uint8 (1)
    ⇒ 2

which becomes difficult for the user to apply uniformly and might allow hard to find bugs to be introduced. The same applies to single precision values where a mixed operation such as

single (1) + 1
    ⇒ 2

returns a single precision value. The mixed operations that are valid and their returned data types are

Mixed OperationResult
double OP singlesingle
double OP integerinteger
double OP chardouble
double OP logicaldouble
single OP integerinteger
single OP charsingle
single OP logicalsingle

The same logic applies to functions with mixed arguments such as

min (single (1), 0)
   ⇒ 0

where the returned value is single precision.

In the case of mixed type indexed assignments, the type is not changed. For example,

x = ones (2, 2);
x(1, 1) = single (2)
   ⇒ x = 2   1
          1   1

where x remains of the double precision type.


Next: , Previous: , Up: Numeric Data Types   [Contents][Index]