Course contentsShow
← C
Lesson 124 of 1,2192. Variables and TypesFree lesson

Automatic conversion in assignments

Automatic conversion in assignments

What you'll learn: How C automatically reshapes data to fit the "container" you assign it to.

In C, variables are like specific containers. An int is a sturdy box for whole numbers, while a float is a glass jar for numbers with decimals. Sometimes, you might try to pour the contents of one into the other. When you do this through an assignment (using the = operator), C doesn't panic; it simply performs "Implicit Type Conversion."

The Shape-Shifter Rule

Think of the assignment operator as a translator. If you have a float with the value 9.99 and you try to shove it into an int variable, C has to make it fit the rules of an integer. Since integers cannot hold decimals, C simply chops off everything after the decimal point. It doesn't round to the nearest number; it just discards the extra data to make the value fit the box.

Similarly, if you put a whole number (like 5) into a float variable, C adds a "decimal tail" to it, turning it into 5.000000. The value is the same, but the format has changed to match its new home.

Seeing it in Action

In the code below, watch how the data changes the moment it crosses the = bridge:

#include <stdio.h>

int main() {
    // 1. Float to Int: The "Clipper" effect
    float pi = 3.14;
    int clippedPi = pi; // The .14 is discarded

    // 2. Int to Float: The "Expander" effect
    int goldCoins = 50;
    float price = goldCoins; // Becomes 50.000000

    printf("Clipped: %d\n", clippedPi);
    printf("Expanded: %f\n", price);

    return 0;
}

Potential Data Loss

It is important to remember that automatic conversion is a one-way street toward the destination variable's type. When you move from a "larger" or more complex type (like a float) to a "smaller" or simpler type (like an int), you lose precision. This is often called "narrowing." C does this quietly without warning you, so you must ensure that losing those decimals won't break your program's logic.

Key takeaway

C automatically converts the value on the right side of an assignment to match the variable type on the left, even if it means chopping off decimal data.