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

Hierarchy of types in expressions

Hierarchy of types in expressions

What you'll learn: How C automatically decides which data type wins when you mix different types in a single calculation.

The "Promotion" Rule

Imagine you are packing a suitcase. You can easily fit a small book into a large trunk, but you can’t fit a large trunk into a small book without breaking something. C follows this same logic when you perform math with different types, such as adding an integer (int) to a decimal (float).

To prevent data loss, C automatically "promotes" the smaller, less precise type to the larger, more precise type before doing the math. This is called the Hierarchy of Types. Think of it as a ladder: the higher the type is on the ladder, the more "power" it has to convert others to its level.

The Ladder of Power

In a standard expression, the hierarchy generally flows upward like this:

  1. long double (Highest)
  2. double
  3. float
  4. unsigned long long
  5. long long
  6. unsigned int
  7. int (Lowest)

If you add an int and a double, C looks at its ladder, sees that double is higher, and temporarily transforms the int into a double. The calculation then happens between two doubles, ensuring the decimal precision isn't chopped off.

Seeing it in Action

Look at how C handles a mix of a whole number and a decimal. Even though both variables represent the number five, their "weight" in the hierarchy is different.

#include <stdio.h>

int main() {
    int cookies = 5;          // A whole number
    float price = 2.5f;       // A decimal number
    
    // C promotes 'cookies' to a float before multiplying
    // Calculation: 5.0 * 2.5
    float total = cookies * price; 

    printf("Total cost: %f", total); // Result: 12.500000
    return 0;
}

In the example above, cookies doesn't actually change into a float permanently in memory. Instead, C creates a temporary floating-point version of that 5 just for the multiplication.

Why it matters

The hierarchy exists to protect your data. If C downgraded a float to an int automatically, a value like 3.99 would become 3, and you would lose the .99 forever. By always moving "up" the ladder toward the most flexible type, C ensures your results stay as accurate as possible.

Key takeaway

In mixed expressions, C automatically promotes the "smaller" type to match the "larger" type to prevent data loss.