Learning All the Things
5
Feb
Casting Variables in C (No, You’re Not Just Bad at Math!)
CS50x, Technology

Warning: I always assume that every error in my programming occurs because I am terrible at math. You can therefore imagine my shock and excitement when I learned that one of my very first errors was NOT due to my lack of mathematical prowess. So without further ado, Casting Variables in C…

What *is* Casting?

Casting is the act of taking one variable type and forcing a variable of another type to adopt its’ attributes in one specific instance.

For example:

int numerator = 20;
int denominator = 7;
float diff = numerator/denominator;

So this program is dividing 20 by 7, so the result should be 2.86 (rounded to 2 places), right?

 

WRONG!

 

But… why?!

Well, C looks at your lines of code with a specific order of precedence, and since the = is pretty low on the totem pole so to speak, your mathematical equation on the right is handled before the type of your answer is considered. So, when you perform a mathematical operation with two integers in C, even if you tell the program to cast the result as a float, it will do the math first, truncating its result at the integer value. Then, it will use that truncated integer result of the equation and convert it into a float.

So, how do you fix it?

This is where the casting comes in! It turns out that all you need to do is tell C that one of your integers should be treated as a float during your operation and voila! C knows that both items must become floats for the mathy goodness to work and thus, your problem is solved.

For example:

int numerator = 20;
int denominator = 7;
float diff = (float)numerator/denominator;

There you have it! The #epiphany I came to from the first debugging instance of my CS50x class.

Questions/Comments?

Feel free to comment here on my blog, or find me on Twitter @DokiDara.

Leave a comment