Menu
CoddyTech

Type Casting Part 1

Part of the Fundamentals section of Coddy's C journey. Lesson 13 of 63.

Type casting in C allows you to convert a value from one data type to another. This is useful when you need to perform operations between different data types.

There are two main types of type casting:

  1. Implicit casting (automatic)
  2. Explicit casting (manual)

Let's start with implicit casting:

Implicit casting happens automatically, for example when you assign a value of a smaller data type to a variable of a larger one:

int num = 10;
double decimal_num;

// Implicit casting from int to double
decimal_num = num;

After executing the above code, decimal_num will have the value 10.0

This conversion is safe because a double can store all possible values of an int without losing any data.

Common implicit casting paths:

  • char → int → long → float → double

The long to float step can lose precision: a float cannot store every long exactly, so 123456789 becomes 123456792.0.

Now let's look at explicit casting:

Explicit casting is done manually by placing the target data type in parentheses before the value you want to convert. Use it when converting from a larger data type to a smaller one, where data loss may occur:

double decimal_num = 5.65;
int num;

// Explicit casting from double to int
num = (int)decimal_num;

After executing the above code, num will have the value 5

Notice that the decimal part is truncated (not rounded) when casting from double to int. The syntax for explicit casting is:

(target_type) value

C would also do this conversion without the cast: num = decimal_num; gives the same 5. Because the conversion can lose data, writing the cast makes it visible and tells the compiler you are aware of the potential data loss.

challenge icon

Challenge

Easy

Write a program that:

  1. Declares a double variable result and sets it to 5.65
  2. Declares an int variable grade
  3. Assigns the value of result to grade using explicit casting

The line below your code prints grade with the message "The grade is: ".

Try it yourself

    double result = 5.65;
    int grade;
    
    // Use explicit casting to convert result (double) to grade (int)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online C compiler