Conversion or casting in C

In C values of one type can be converted to the equivalent of another type in two ways, explicitly and implicitly. In either case, conversion is only meaningful where a valid equivalent exists.

For a full list of conversions you should refer to a good textbook. Here we just consider the general principles.

Implicit casting

ANSI C generally knows what type has been declared for a variable, a parameter and return type. Whenever you use a value in these contexts it can be checked to see that it matches the use to which it is being put. If it has a sensible conversion defined, it will be converted and used. If there is no sensible conversion, it will be reported as a compiler error.

In general arithmetic types are convertible into each other. In some cases, such as int to float, this will be exact. In others, such as double to float, there may be some loss of range or accuracy. You should take care to avoid errors due to implicit casting.

Pointer values can be converted into other pointer types. This allows an area of memory to be accessed as if it was made up of different elements, but is extremely unsafe. In general the only time this is done is when a void * pointer is being returned from a function such as malloc.

Explicit casting

To make sure you are in control, it is often better to use explicit casting. This is done by writing the type you want to convert a value into inside parentheses in front of the value. It is most useful when creating a pointer to a new struct returned from malloc.


Back to the Contents page.