Mixed Mode Expressions in C++ - dummies

Mixed Mode Expressions in C++

By Stephen R. Davis

C++ allows you to mix variable types in a single expression. That is, you are allowed to add an integer with a double precision floating-point value. In the following expression, for example, nValue1 is allowed to be an int:

// in the following expression the value of nValue1
// is converted into a double before performing the
// assignment
int nValue1 = 1;
nValue1 + 1.0;

An expression in which the two operands are not the same type is called a mixed mode expression. Mixed mode expressions generate a value whose type is equal to the more capable of the two operands. In this case, nValue1 is converted to a double before the calculation proceeds. Similarly, an expression of one type may be assigned to a variable of a different type, as in the following statement:

// in the following assignment, the whole
// number part of fVariable is stored into nVariable
double dVariable = 1.0;
int nVariable;
nVariable = dVariable;

You can lose precision or range if the variable on the left side of the assignment is smaller. In the preceding example, C++ truncates the value of dVariable before storing it in nVariable.

Converting a larger value type into a smaller value type is called demotion, whereas converting values in the opposite direction is known as promotion. Programmers say that the value of int variable nVariable1 is promoted to a double in expressions such as the following:

int nVariable1 = 1;
double dVariable = nVariable1;

Mixed mode expressions are not a good idea. Avoid forcing C++ to do your conversions for you.