C Programming Tutorial 39 – Implicit Type Promotion

The previous blog was foundational to this blog, so go read that first! Are you new here? Start at the beginning, Intro to C!

Essentially, casting is when something of a certain data type is converted to a different data type.

This blog is going to be showing examples of both implicit casting and explicit casting. When you study implicit conversion in C, you will likely come across the term promotion.

This article talks about implicit conversion, and the section on promotion talks about what data types can be converted to other data types without loss of information.

http://en.cppreference.com/w/cpp/language/implicit_conversion

A common example of this is when we pass floats to functions.

float x = 50.0f;  // You can put the f here if you want to be specific that this is a float, but either way should work just the same).

The printf function actually takes the x as a double. This means that 50.0f is promoted to 50.0. If we are talking about constant values, a float value always has an f. If you leave the f off, it is assumed to be of type double. You can use the %f conversion character for both floats and for doubles because they are actually always being printed as doubles… Even if you pass in a float.

Now, it’s important to understand that the actual value or data type does not change. The variable x is still of type float.

Another common type of implicit conversion is when we are doing assignment. If we have something such as this:

The integer 60 is implicitly casted to a double. That’s because an integer can fit inside of a double without losing data.

Sometimes, it’s not that easy and we risk losing data. That’s what we are going to be talking about in the next blog! Read it now!

Leave a Reply

Your email address will not be published. Required fields are marked *