The Curse of Typecasting – Solution

I hope you didn’t find this month’s Exercise too daunting. In fact, it’s pretty basic stuff, but often something you might forget. In fact, the compiler may remind you when you attempt to pass an argument to a function and it’s of the wrong type.

Here’s my solution:

#include <stdio.h>

int main()
{
    int apple = 65;

    printf("As integer: %d\n",apple);
    printf("As character: %c\n",(char)apple);
    printf("As float: %f\n",(float)apple);

    return(0);
}

Variable apple is assigned value 65 in Line 5. It’s an int variable and 65 is an integer value.

Line 7 prints variable apple‘s value as an integer; the printf() placeholder %d is used and the variable doesn’t need to be typecast.

Line 8 typecasts apple to a char variable. The %c placeholder is used, therefore the value is interpreted as a character and displayed as such.

Finally, Line 9 typecasts apple to a float value, with %f doing the heavy lifting to show the value as a real number.

Here’s the output:

As integer: 65
As character: A
As float: 65.000000

Because a char variable is a type of integer, you don’t have to typecast in Line 8; you still get the same results. You must, however, typecast in Line 9. It’s the fact that you can treat a char as a character or integer that makes C a weak-type language. Other programming languages use stronger variable types, where you can’t treat a value of one type as another.

Most frequently, you use typecasting when a specific variable type is required as a function argument. For example, the function needs an int but you’re using a float. In that instance, you must typecast the variable to match the requirements of the function.

Typecasting becomes a big issue with pointer arguments as the function most definitely must know what type of storage lurks at the variable’s location in memory. Frequently, you’ll use a typecast with the NULL constant — which isn’t zero, but rather a pointer. You must typecast the NULL so that it matches the required variable type, such as (char *)NULL. Be on the lookout for those instances when typecasting is a must.

Leave a Reply