Menu
Coddy logo textTech

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) expression

Let'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 icon

Challenge

Easy

Write a program that:

  1. Declares a double variable named temperature and assigns it a value of 98.6.
  2. Uses explicit type casting to convert temperature to an integer and stores it in a variable named whole_part.
  3. 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) expression

Converting float to integer (truncates decimal part):

float price = 45.95;
int rounded_price = (int) price;  // Result: 45

Converting character to integer (gets ASCII value):

char letter = 'A';
int ascii_value = (int) letter;  // Result: 65

Note: 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;
}
quiz iconTest yourself

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

All lessons in Fundamentals