Type Conversion & Casting in C

Type Conversion & Casting in C


Introduction

In C programming, sometimes we need to convert one data type into another. This process is called Type Conversion.

👉 It is very useful when performing operations between different data types.

There are two types:

  • Automatic Type Conversion
  • Type Casting (Manual Conversion)

What is Type Conversion?

Type conversion means converting a value from one data type to another.

👉 Example:

int a = 10;
float b = a; // int → float

1. Automatic Type Conversion (Implicit Conversion)

This is done automatically by the compiler.

👉 Smaller data type → Bigger data type


Example

#include <stdio.h>

int main() {
int a = 10;
float b;

b = a; // automatic conversion

printf("Value of b = %f", b);

return 0;
}

Output

Value of b = 10.000000

Key Points

  • ✔ Done automatically
  • ✔ No data loss
  • ✔ Safe conversion

2. Type Casting (Explicit Conversion)

Type casting is done manually by the programmer.

👉 Syntax:

(data_type) expression

Example

#include <stdio.h>

int main() {
float a = 5.8;

int b = (int)a; // manual conversion

printf("Value of b = %d", b);

return 0;
}

Output

Value of b = 5

Explanation

  • float 5.8 → converted to int
  • Decimal part is removed
    👉 Result = 5

Difference Between Type Conversion & Type Casting

Feature Type Conversion Type Casting
Control Automatic Manual
Done By Compiler Programmer
Syntax No syntax needed (data_type)
Data Loss No Possible

Common Mistakes

  • ❌ Ignoring data loss during casting
  • ❌ Using wrong data type
  • ❌ Confusing implicit and explicit conversion

Pro Tips

  • ✔ Use casting carefully
  • ✔ Prefer automatic conversion when safe
  • ✔ Always check precision loss
  • ✔ Practice mixed data type operations

Conclusion

Type conversion and casting are important concepts in C programming. They help in handling different data types efficiently and ensure smooth program execution.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C