Casting In C

Tifu Kelison Tifu Kelison
2 min read

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.

Screenshot 2022-11-07 at 00-37-13 Online C Compiler.png

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.

0
Subscribe to my newsletter

Read articles from Tifu Kelison directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tifu Kelison
Tifu Kelison

I am a Graphic Designer and Front-end developer and UI Designer(still in process) from Cameroon. I am the founder and CEO of the Design Archive. I love to write and as it turns out, hashnode is just the community I needed to start doing that. I at the time of writing this bio, I'm in my first year of university that's why you see writing articles about C. If you ever what to chat, feel free to hit me up on any social media platform.