Typecasting in C

Han sang yeob·2021년 1월 31일
0

Basic of C language

목록 보기
3/9

Type casting

We can put C as a really really grumpy man. Let's assume that you borrowed 1000won(in paper money) from that grumpy man. so, you bought a nice piece of chocolate bar with 1000won and a few days later, you found 10 of 100won coin in your piggy bank. You will give back the grumpy man 10 coins of 100won. But the old grumpy man says, "Hey! what is this?? I gave you 1000won in paper money!". So, you went to the bank and exchanged 10 coins of 100won into a 1000won bill and settled your debt. The act of going to the bank is what we call typecasting in C.

C programming is a strongly typed language. This means every piece of data has specific types. Once the value has been declared it's a datatype, it won't change the datatype again! However, we are able to case it to a different datatype but it won't change it's an essential value.
Unlike C, there are loosely typed language of course like JavaScript.(or we can say not quite straight as much as C).

For example, the result of 1/3 will be 0 in C but in lossly typed language, it will be printed as 0.333...

There are two types of typecasting in C. Implicit and explicit.

1. Implicit

Implicit is loseless way to typecast your data in automatic way.

ex) int x -> double x
1 -> 1.00

  • In here, we didnt lose our data at all.

Example in code:

#include <stdio.h>

int main()
{
// implicit type conversion - promotion
    float x = 50.0;
    printf("%f",x); // printf takes a double
    // we can say x is PROMOTED! - the value of x is stored as a double
    
//or
    double y = 50.0f;
    printf("%f",y);
    //this is also okie because double is bigger than float. No data loss
    return 0;
}

2. Explicit

We need to tell the computer to do it
ex) double x -> int x
1.85 -> 1.00

  • we lost 0.85 :( We can say like"The data is truncated."

Example in code


#include <stdio.h>

int main()
{
    int slices = 17;
    int people = 2;
    
    /* Two ways to fix this:
    1. add .0 to a constant
    2. explicit type casting
    */
    
    double halfThePizza = (double)(slices / people);
    //!=
    double halfThePizza2 = (double)slices / people;
    //in here (double) is an unary operator which will not change the value.
    //(double) have higher precedence

    printf("%f\n",halfThePizza);
    printf("%f\n",halfThePizza2);
    

    return 0;
}
profile
Learning IT in Vietnam

0개의 댓글