C
Type Casting and Conversion
Data Types & Expressions

Type Casting and Type Conversion

Understanding how C handles mixed data types automatically, and how to force conversions safely.

What happens when you calculate 5 / 2 and assign it to a float?
This is the classic "Integer Division Trap." Students naturally assume math works like a calculator. We use this to bridge into why explicit type casting is necessary.
division_trap.cExpression
int a = 5; int b = 2; float result = a / b; // Output: 2.000000 printf("%f", result);
int5
/
int2
Step 1: The compiler evaluates the right side first. Because both 5 and 2 are integers, it prepares for Integer Division.
Implicit Conversion (Coercion)

The Compiler's Automatic Ladder

Type Promotion

When evaluating mixed-type expressions, C automatically "promotes" smaller or less precise types to match the largest/most precise type involved to avoid data loss.

long double
double
float
unsigned long long
long long
long
unsigned int
int
1

int + double

The int is converted to a double before the addition takes place. The result is a double.

5 + 2.5 → 5.0 + 2.5
2

char + int

The char is promoted to an int (using its ASCII value) before addition.

'A' + 1 → 65 + 1
Explicit Casting

Taking Control of Types

Use the cast operator (type) to explicitly force an expression to become a specific type.

The Integer Division Fix

7 / 2
3.000000
Integer division truncates the decimal before assigning to float.

How it works

float result = (float)7 / 2;
  • The cast operator (float) has higher precedence than division.
  • It temporarily converts 7 to 7.0f.
  • Because one operand is now a float, the compiler automatically promotes the 2 to 2.0f.
  • Floating-point division is performed.
Data Demotion (Narrowing)

When Data is Lost

Converting a larger or more precise type into a smaller or less precise type often results in data loss or truncation.

Float to Int Truncation

Assigning a floating-point number to an integer drops the fractional part entirely. It does NOT round.

3 .14159
int x = (int)3.14159; // x becomes 3

Int to Char (Overflow)

A char typically holds 8 bits (-128 to 127). Forcing a larger integer into it chops off the higher-order bits.

Resulting char value (Decimal):
44
300 % 256 = 44. The excess data is discarded.
Knowledge Check

Test Your Understanding

Question 1 of 5
Ask students to solve the expression visually before clicking the answer. Remind them of precedence rules combined with casting.
Final recap

Key Takeaways

Promotion is Safe

Moving from a smaller type (int) to a larger type (double) happens automatically and preserves data.

Demotion is Risky

Moving from a larger type to a smaller type forces data loss, truncation, or unexpected overflow.

( )

Be Explicit

Use the (type) cast operator to clarify your intentions, especially to prevent integer division traps.