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:
- Implicit casting (automatic)
- Explicit casting (manual)
Let's start with implicit casting:
Implicit casting happens automatically when converting from a smaller data type to 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 works because a double can store all possible values of an int without losing any data. The conversion is safe, so C does it automatically.
Common implicit casting paths:
- char → int → long → float → double
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. This is necessary 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) valueBecause this conversion can lose data, C requires you to do it explicitly — this tells the compiler you are aware of the potential data loss.
Challenge
EasyWrite a program that:
- Declares a double variable
resultand sets it to 5.65 - Declares an int variable
grade - Assigns the value of
resulttogradeusing explicit casting - Prints the value of
gradewith the message "The grade is: " using printf
Cheat sheet
Implicit casting — automatic conversion from smaller to larger type:
int num = 10;
double decimal_num = num; // becomes 10.0Common implicit casting path: char → int → long → float → double
Explicit casting — manual conversion using (target_type) value:
double decimal_num = 5.65;
int num = (int)decimal_num; // becomes 5 (truncated, not rounded)Use explicit casting when converting from a larger type to a smaller one, where data loss may occur.
Try it yourself
#include <stdio.h>
int main() {
double result = 5.65;
int grade;
// Use explicit casting to convert result (double) to grade (int)
printf("The grade is: %d\n", grade);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge