Flipkart.com

II.13: When should a type cast be used?

Answer:
There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly. If you have read II.12, the following listing should look familiar. The variable f1 is set to the result of dividing the integer i by the integer j. The result is 0, because integer division is used. The variable f2 is set to the result of dividing i by j as well.
However, the (float) type cast causes i to be converted to a float. That in turn causes floating-point division to be used (see II.11) and gives the result 0.75.

#include
main()
{
int i = 3;
int j = 4;
float f1 = i / j;
float f2 = (float) i / j;
printf(“3 / 4 == %g or %g depending on the type used.\n”,
f1, f2);
}

The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. For example, the following line type casts the return value of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));

Reference:
II.6: When should the volatile modifier be used?
II.8: When should the const modifier be used?
II.11: Are there any problems with performing mathematical operations on different variable types?
II.12: What is operator promotion?
II.14: When should a type cast not be used?
VII.5: What is a void pointer?
VII.6: When is a void pointer used?
VII.21: What is the heap?
VII.27: Can math operations be performed on a void pointer?

No comments:

Post a Comment