what is it exactly i dont' quite understand. can some one explain? thanks
what is it exactly i dont' quite understand. can some one explain? thanks
C has rules on what type one variable is vs another in order to protect you from making mistakes. Type casting is for when you want to break such a rule.
Or it is used as the conversion that it is, when applicable.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Every value is made up of a bit pattern and a type. The bit pattern doesn't change, but just a bit pattern isn't useful. The type tells C how to represent the bit pattern. An example is that the bit patten 01000001 represented as an int is 65, but represented as a char it's 'A'. The bit pattern doesn't change, but the type it's represented as does.
Type casting is when you force C to use the representation you want. The representation you want might not be possible, but a type cast also tells C to assume it is. That's why it's easy to crash a program if you aren't careful with type casts.
And in the case of an actual conversion (such as floating point to integral), the actual bit pattern can change. Other conversions may relate to the size of the object, which obviously also deals with an underlying bit pattern.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
The easiest way to guarantee the bit pattern does not change is to to make a pointer, cast it to the correct type and dereference it. You may have to do this with some troublesome types such as float or double. But it may not give you the result you expect if you do:
Code:float f = 1.0f; int n1 = (int)f; /* n1 == 1 */ int n2 = *(int*)&f; /* This one won't be what you expect, but the bit pattern is intact. */