4 Casting

In C/C++, the type of an expression can be altered by casting. Some casting is done automatically, consider the following fragment of code:

short int i;
long int j;

j = i;

Because i is a short integer, it needs to be promoted to a long integer before being copied to j. This is done automatically.

Using the same set up, i = j; is done automatically as well. However, this is a demotion, and can lead to the loss of significant digits. A compiler usually generates a warning.

If you think you know what you are doing, you can silence the compiler by using the following statement:

i = (short int)j;

This is explicit casting. You are, essentially, telling the compiler that you know there is a demotion, and that's okay with you.

Casting is particularly useful with void pointers. Consider the following;

void sub1(void *p)
{
  ...
}

The subroutine really cannot do anything with parameter p because it is a pointer that has no type. However, you can type cast it first, then use the casted result to perform operations:

*(int*)p = 23;

This statement says that you want to make p an integer pointer. Then, copy the value 23 to whatever integer p points to.

Void pointers may seem unnecessary, but they are quite handy in object-oriented programming with plain C. With C++, the necessity to use void pointer is mostly eliminated.

Copyright © 2006-09-25 by Tak Auyeung