🔄 Type Conversion in C Language

Implicit and Explicit Type Conversion

🔹 What is Type Conversion?

Type conversion in C is the process of converting one data type into another. It is mainly used when an operation involves different data types.

Example:
int a = 10;
float b = 5.5;
float result = a + b; // int converted to float

Article Algo

📌 Types of Type Conversion in C

C supports two types of type conversion:

Type Description
Implicit Type Conversion Automatically done by the compiler
Explicit Type Conversion Manually done using type casting

Article Algo

1️⃣ Implicit Type Conversion (Automatic)

  • Done automatically by the compiler
  • Occurs when mixed data types are used
  • Lower data type is converted to higher data type
Order of Conversion:

char → int → float → double

Example:
#include <stdio.h>
int main() {
  int a = 5;
  float b = 2.5;
  float result = a + b;

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

2️⃣ Explicit Type Conversion (Type Casting)

  • Done manually by the programmer
  • Used to control conversion
Syntax:
(type) expression
Example:
#include <stdio.h>
int main() {
  int a = 10, b = 3;
  float result = (float)a / b;

  printf("Result: %.2f", result);
  return 0;
}
Output:
Result: 3.33

❓ Why Type Conversion is Needed?

  • To avoid data loss
  • To get accurate results
  • To control expression evaluation
Example Showing Need for Type Casting:
#include <stdio.h>
int main() {
  int a = 5, b = 2;

  printf("Without casting: %d\n", a / b);
  printf("With casting: %.2f\n", (float)a / b);

  return 0;
}
Output:
Without casting: 2
With casting: 2.50

📚 FAQs on Type Conversion in C

Q1. What is implicit type conversion?

It is automatically performed by the compiler when different data types are used.

Q2. What is explicit type conversion?

It is done manually by the programmer using type casting.

Q3. Which type conversion is safer?

Explicit type conversion is safer because the programmer controls it.

Q4. Can data loss occur during type conversion?

Yes, converting larger data types to smaller ones may cause data loss.

Q5. What happens when float is converted to int?

The decimal part is discarded.

🔑 Key Points to Remember

  • Implicit conversion is automatic
  • Explicit conversion uses type casting
  • Smaller → larger is safe
  • Larger → smaller may cause data loss