Type Casting Part 2
Part of the Fundamentals section of Coddy's C journey — lesson 14 of 63.
In Part 1, we looked at implicit type casting. Now, let's explore explicit type casting in C.
Explicit type casting (manual conversion) is when you forcefully convert one data type to another using the cast operator.
The syntax for explicit casting is:
(target_type) expressionLet's convert a float to an integer:
float price = 45.95;
int rounded_price = (int) price;After executing the above code, rounded_price will be:
45
Notice that the decimal part is truncated (not rounded).
We can also cast characters to integers to get their ASCII values:
char letter = 'A';
int ascii_value = (int) letter;After executing the above code, ascii_value will be:
65
Remember, type casting can lead to data loss, especially when converting from a larger data type to a smaller one.
Challenge
EasyWrite a program that:
- Declares a double variable named
temperatureand assigns it a value of 98.6. - Uses explicit type casting to convert
temperatureto an integer and stores it in a variable namedwhole_part. - Prints the original temperature and the whole part on separate lines.
Example output:
Original temperature: 98.6
Whole part: 98
Cheat sheet
Explicit type casting in C allows you to manually convert one data type to another using the cast operator.
Syntax:
(target_type) expressionConverting float to integer (truncates decimal part):
float price = 45.95;
int rounded_price = (int) price; // Result: 45Converting character to integer (gets ASCII value):
char letter = 'A';
int ascii_value = (int) letter; // Result: 65Note: Type casting can lead to data loss when converting from larger to smaller data types.
Try it yourself
#include <stdio.h>
int main() {
// Write your code here
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