Course contentsShow
← C
Lesson 231 of 1,2193. Operators and ExpressionsFree lesson

Truncation during casting

Truncation during casting

What you'll learn: How to avoid data loss when forcing a large number type into a smaller one through explicit casting.

The "Big Box, Small Box" problem

Imagine you have a large shipping box that can hold 50 books, and a small shoebox that can only hold 5 books. If you try to dump the contents of the large box into the small one, you don’t magically get smaller books; the extra books simply spill over and are lost.

In C, "truncation" is what happens when you take a data type with a large capacity (like a double or a long) and force it into a type with a smaller capacity (like an int or a char). Because the destination doesn't have enough "bits" to store the original value, the extra information is chopped off.

Chopping off the decimals

The most common form of truncation happens when casting a floating-point number (with decimals) to an integer. C does not round to the nearest whole number; it simply deletes everything after the decimal point.

If you have 9.99 and cast it to an integer, you don't get 10. You get 9. The .99 is discarded forever.

Overflow truncation

Truncation also happens between whole numbers of different sizes. If you try to cast a large int into a char (which usually only holds values up to 127 or 255), C chops off the "high-order" bits. The result is often a seemingly random, smaller number that bears no resemblance to your original data.

#include <stdio.h>

int main() {
    double precisePi = 3.14159;
    
    // Explicitly casting double to int causes truncation
    int truncatedPi = (int)precisePi; 
    
    printf("Original: %f\n", precisePi);    // Output: 3.141590
    printf("Truncated: %d\n", truncatedPi); // Output: 3
    
    // Truncating a large int into a char
    int bigNumber = 300;
    char smallStorage = (char)bigNumber;
    
    // Result will not be 300; it will be 44 due to bit loss
    printf("Small storage: %d\n", smallStorage); 
    
    return 0;
}

Why does this matter?

C trusts you. If you use a cast, you are telling the compiler, "I know what I'm doing." The compiler will not warn you that you are losing data. You must be certain that the value you are converting actually fits into the new, smaller container, or that you truly don't care about the decimal remainder.

Key takeaway

Casting from a larger type to a smaller type causes truncation, where decimal values are dropped or bits are lost without rounding.