Expert C Programming

(Jeff_L) #1

(float) 3


it's a type conversion and the actual bits change. If you say


(float) 3.0


it's a type disambiguation, and the compiler can plant the correct bits


in the first place. Some people say that casts are so-named because


they help something broken to limp along.


It is easy to cast something to an elementary type: write the name of the new type (for example, int)
in brackets before the expression you wish to cast. It is not quite so obvious how to cast to a more
complicated type. Say you have a pointer to a void that you know actually contains a function pointer.
How do you do the typecast and call the function all in one statement?


Even complicated casts can be written following this three-step process.



  1. Look at the declaration of the object to which you wish to assign the casted result.

  2. Remove the identifier (and any storage class specifiers like extern), and enclose what
    remains in parentheses.

  3. Write the resulting text immediately to the left of the object you wish to cast.


As a practical example, programmers frequently discover that they need to cast to use the qsort()
library routine. The routine takes four parameters, one of which is a pointer to a comparison routine.
Qsort is declared as


void qsort(void *base, size_t nel, size_t width,


int (compar) (const void , const void *));


When you call qsort() you will provide a pointer to your favorite comparison routine as argument
compar. Your comparison routine will take an actual type rather than void * arguments, so will likely
look somewhat like this:


int intcompare(const int i, const int j)


{


return(i - j);


}


This does not exactly match what qsort expects for argument compar() so a cast is required. [2] Let's
assume we have an array a of ten integers to sort. Following the three step cast process outlined above,
we can see that the call will look like


[2] If you have a perverse and unpopular computer that makes the size of a pointer vary


according to the type it points to, then you will have to do the cast in your comparison routine,
rather than the call. Try to move to a better designed architecture as soon as possible.


qsort(


a,

Free download pdf