C Type Casting

Type casting means converting a value from one data type to another. It can happen automatically (implicit) or you can do it yourself (explicit).

Implicit conversion

The compiler converts the smaller type to the bigger type in an expression.

#include <stdio.h>

int main(void) {
    int a = 5;
    float b = 2.5f;
    float result = a + b;     // a becomes float

    char c = 'A';
    int code = c;             // char becomes int

    printf("%.1f\n", result);
    printf("%d\n", code);
    return 0;
}

Output:

Output of the above program is

7.5
65

Explicit conversion (cast)

Write the new type in brackets before the value. This is useful in division, because dividing two int values gives an int.

#include <stdio.h>

int main(void) {
    int total = 7, count = 2;

    printf("Without cast: %d\n", total / count);
    printf("With cast: %.2f\n", (float)total / count);
    return 0;
}

Output:

Output of the above program is

Without cast: 3
With cast: 3.50

Here (float)total is converted first, and then the division happens in float. Without it, 7 / 2 is integer division and the decimal part is lost.

Float to int

#include <stdio.h>

int main(void) {
    float price = 99.99f;
    int rounded = (int)price;   // cuts the decimal part

    printf("%d\n", rounded);
    return 0;
}

Output:

Output of the above program is

99

Note: Converting float to int does not round the number. It cuts the decimal part (99.99 becomes 99). Cast the variable, not the whole division: (float)(a / b) is wrong, because the integer division is already done.

Next: C Operators.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.