C Type Conversion: Full Guide for Beginners

In C programming, type conversion refers to changing a variable from one data type to another. It can happen automatically (implicit) or manually (explicit or type casting).

Let’s explore this in a simple, step-by-step guide.

What is Type Conversion in C?

Implicit Type Conversion (Type Promotion)

Also called automatic conversion. The compiler automatically converts the smaller data type to a larger one.

 Example:

#include <stdio.h>

int main() {
    int x = 5;
    float y = 2.5;
    float result = x + y; // int is promoted to float

    printf("Result = %.2f\n", result); // Output: 7.50
    return 0;
}

Type Hierarchy (Lower → Higher):

charintfloatdouble

Explicit Type Conversion (Type Casting)

Manually convert one data type to another using a cast operator.

Syntax:

(type) expression;

Example:

#include <stdio.h>

int main() {
    float num = 5.75;
    int converted = (int) num; // Manual type casting

    printf("Converted = %d\n", converted); // Output: 5
    return 0;
}

Note: Decimal part is truncated, not rounded.

More Examples of Type Conversion

Example 1: Implicit Type Conversion in Expression

int a = 10;
char b = 'A'; // ASCII 65
int result = a + b;  // b is promoted to int

Example 2: Explicit Conversion in Division

int a = 5, b = 2;
float result = (float)a / b; // Prevents integer division

Table: Implicit Conversion Example

Operand 1Operand 2Result Type
intfloatfloat
charintint
floatdoubledouble

Best Practices

  •  Use type casting to avoid precision loss
  •  Use float or double when working with decimals
  • Be careful when converting float to intdecimals will be dropped

Common Mistakes to Avoid

MistakeWhy it’s Wrong
Mixing int and float without castCauses truncation or wrong result
Forgetting to cast in divisionResults in integer division
Assuming automatic roundingCast only truncates