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
Write a C program to swap the values of two variables using a third variable
Write a C program to print words using spacing and new line characters
Write a C program to get the salary from the user and print it
Write a C program to find the size of int, float, long, double and char
Write a C program to get the marks of 5 subjects and find the total and average
Write a C program to calculate the perimeter of a rectangle
Write a C program to convert minutes into hours and minutes
Interview Questions & Answers
What is the difference between a variable and a constant in C?
What are the data types in C?
What is the difference between = and == in C?
What is the difference between ++i and i++ in C?
What is the use of the sizeof operator in C?
How to swap two numbers in C?