C Language Reference for Script Programmers - Typecasting

Typecasting

Overview                                                                                                                                                                       

Typecasting is kind of a tricky subject. It’s one of the pieces of C that people either love or they hate. The reason for this is that typecasting is at once both powerful and dangerous.

Typecasting allows you to assign the value of one item to another when the two do not have the same data type.

Example                                                                                                                                                                       

int  myInt = 0;
float myFloat = 7.0; 

myInt = myFloat;

If you attempt the above your compiler’s going to start complaining. You can avoid this problem by using typecasting.

In the assignment of myFloat to myInt you can explicitly tell the compiler that you want it to treat myFloat as if it were an integer:

myInt = (int)myFloat;

By putting (int) in front of myFloat we are typecasting it from a float to an int. What we end up with is myInt with a value of 7. We run into problems however when the value of the float is something like 3.1415. An int cannot have a fractional component so it must be dropped, the resulting value would be 3. So would 1.6 be changed to 2? No. There is no rounding when typecasting, the resulting value would simply be 1.

This can actually be very useful when you need to get the whole number component of a float or double. Just typecast it to an int and you’re all set. Now the float minus the double gives you the fractional component (or modulo 1).

When you don’t want to use typecasting                                                                                                                    

Well this is really kind of common sense. You only every want to use typecasting when it makes sense, when there is something in common between the two types. Remember our item structure from the previous section? What if we did this:

item      myItem;
int       myInt = 2; 

myItem = (item)myInt;

Does that make any sense? No, of course not; so don’t do it. There are some special circumstances when you would do something like that, but you should know a lot more C than this doc covers before you get into that.

When you will commonly use typecasting                                                                                                                  

Commonly you will use typecasting to convert an int to a float or vice versa. Also you’ll use it to convert a char to an int when you’re dealing with colors.

The most common typecasting type deserves it’s own section, and it’s got one: Polymorphism. Until you've read that section try to stick with the int<->float, and int<->char conversions only.

Converted from CHM to HTML with chm2web Pro 2.82 (unicode)