Casting In C
What if I told you, that you could divide an integer by another integer and get a double or float as a result?
Well, it's possible, and I'll show you how. But first, let's understand what casting is.
Converting one datatype to another is called type casting or call it casting or type-conversion. For example, if you want to store a 'long' value to an integer, then you just cast 'long' to 'int'.
You can convert from one datatype to another in C by using the cast operator as follows:
(datatype) expression
Consider the example below and make sure to try it out for yourself. I'll leave a link at the end of this article where I usually run my C code online without having to open a text editor every time. You can try out the code there even on your mobile device.
#include<stdio.h>
int main(void) {
int num1 = 17;
int num2 = 2;
double divide = 0.0f;
divide = (double) num1 / num2;
printf("The value of divide is: %f\n",divide);
return 0;
}
Now, basically what the code does is that it takes two integer numbers, casts their type into a double(real numbers), and then outputs it as if they were doubles or floats from the beginning. The image below shows the output of the code.
And that's basically it for casting in c. Thanks for reading. Let me know if you want to add or remove anything or even simple just a question.
Here's the link to online editor.
Until next time.
Peace.