C++ Implicit Conversions

C++ is strongly typed. However it’s worth noting that some conversions happen automatically. These implicit conversions are usually seen with with primitive data types (but not only, more on that here!). A common example is pointer checks. Such conversions are called Standard Conversions.

A standard conversion to a bigger data type (ex: int to float) is known as promotion. In this case, values are preserved. Other standard conversions may not guarantee this and values may get truncated. The data loss may trigger a warning and some projects may treat such warnings as errors. However, this may still be desirable. For example, a speed value might be stored as a float but we want to display it as an int to emulate a real-world speedometer.

    float distance = 107;
    float time = 1.2f;
    float speed = distance / time;
    int speedometerValue =  speed; * yields warning

In such a scenario, we need to use either an explicit conversion or casting.

Explicit conversion is done with the Explicit Type Conversion operator i.e (). This is a functional style way of converting types since it looks like you’re calling a function.

    float speed = 12.5;
    int speedUI = int(speed);

Casting is done with the Cast operator which looks just like the Explicit Type Conversion operator i.e. (). This is the C-style way of casting since it resembles casting in C language.

    float speed = 12.5;
    int speedUI = (int) speed;

C-style Casting is great for simpler data types but once you start working with pointers, it gets a little dangerous. Look at the following:

struct PointUV { float u, v; };
struct Point3D { float x, y, z; };

int main()
{
    PointUV center;
    center.u = 10.5f;
    center.v = 5.25f;
    Point3D* vertex = (Point3D*) &center;

Here, we grab the pointer to the center and cast it to a pointer of a different struct. This is legal; it compiles. You can also properly access vertex’s x and y floats and you’ll get 10.5 and 5.25! However, vertex.z is an uninitialized float value. And once the structs’ type change, all bets are off and you should expect errors and unpredictable values. For this reason, it’s better to directly use Casting Operators.

 Date: September 22, 2018
 Tags:  notes cpp

Previous
⏪ Rebinding Dead Cells

Next
C++ Casting ⏩