Promoting conversions

In a mixed type expression, the compiler will attempt to promote smaller types to the larger type. So, a char or a short can be used in an expression where an int is needed because it can be promoted to the larger type with no loss of data.

Consider a function declared as taking a parameter that is an int:

    void f(int i);

We can write:

    short s = 42;     f(s); // s is promoted to int

Here the variable s is silently converted to an int. There are some cases that may appear odd:

    bool b = true;     f(b); // b is promoted to int

Again, the conversion is silent. The compiler assumes you know what you are doing and that your intention is that you want false treated as 0 and true treated as 1.

Get Beginning C++ Programming 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.