Type Conversions
In an arithmetic expression, binary operators require operands of the same type. If this is not the case, the type of one operand must be converted to match that of the other operand. When calling a function, the argument type must match the parameter type; if it doesn’t, the argument is converted so its type matches. C++ has cast operators, which let you define a type conversion explicitly, or you can let the compiler automatically convert the type for you. This section presents the rules for automatic type conversion.
Arithmetic Types
An arithmetic type is a fundamental
integral or floating-point type: bool
, char
, signed
char
, unsigned
char
, int
, short
, long
, unsigned
int
, unsigned
short
, unsigned
long
, float
, double
, or long
double
. Some operations are permitted only
on arithmetic types, pointer types, enumerations, class types, or some
combination of types. The description of each operator tells you which
types the operator supports.
Type Promotion
Type promotion is an automatic type conversion that applies only to arithmetic types, converting a “smaller” type to a “larger” type while preserving the original value. Contrast promotions with other automatic type conversions (described in later subsections), which can lose information. Promotions involve either integral or floating-point values. The rules for integral promotion are:
A “small” integral rvalue is converted to an
int
if the typeint
can represent all of the values of the source type; otherwise, it is ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.