C Programming Tutorial 38 – Type Casting

Did you read the last blog on Strongly Typed Vs Loosely Typed Languages? Are you new here? Start at the beginning, Intro to C!

In the previous video we mentioned how C was a strongly typed language. Imagine C as a grumpy old man who you owe a dollar bill to. Well, he wants his money now, but all you have is some change.

You look at your change, grab four quarters, and find out that it adds up to exactly a dollar. But unfortunately, you owe him a dollar bill, not just 100 cents. So yeah, he beats you over the head with his cane.

That is the way you ought to look at data types in C. You could say that the guy wanted 1 dollar, but you gave him .25 + .25 + .25 + .25 = 1.00. This my friend is unacceptable.

Well, to fix this problem, you could go the bank, exchange your four quarters for an actual dollar, and then go pay the man. The bank in this situation has fixed your problem by converting your change to whole dollars. In computer science terminology, you can say that your number of the double data type was casted to a number of the integer data type.

Types of Type Casting

So, type casting is the process of converting one data type to another.

There are two main categories of type casting, implicit and explicit type casting.

Implicit type casting is when the conversion happens automatically and you do not have to worry about it.

Explicit type casting is when you have to say specifically that you want to convert some data from one data type to another. You can think of this as “explicitly” telling the computer what to do. It’s not just assumed.

In general, you can think of the implicit type casting as “lossless”. A good example of this is converting an integer to a double. If you convert 1 to 1.00, nothing is lost.

You can think of explicit type casting as “lossy”. For example, if you convert the double value 2.54 to an integer, you truncate the number down to 2.

An example of implicit conversion is if you assign 1 to a double value. You gave the assignment operator an integer, but it gets stored as a double. There’s really nothing you have to do.

The easiest way to explicitly type cast is to use an operator where you put the type you want the value to be in parenthesis before the data. For example, we could do something like (int) 2.5. This will convert the 2.5 to 2 (an integer).

In the next video we will be going over some examples of implicit and explicit conversions and some things to look out for that can cause problems.

In the next blog we are going to be discussing all of the Implicit Type Promotion. Check it out!

Leave a Reply

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