C Type Conversion

1. What is Type Conversion?

  • Type conversion is the process of converting a value from one data type to another.

  • C supports two types of conversions:

    1. Implicit Conversion (Type Promotion)

    2. Explicit Conversion (Type Casting)


2. Implicit Type Conversion (Type Promotion)

  • Also called automatic type conversion.

  • Happens when C automatically converts a smaller data type to a larger data type to avoid data loss during operations.

Example:

#include <stdio.h>

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

result = a + b; // 'a' is implicitly converted to float
printf("Result: %.2f\n", result);

return 0;
}

Output:

Result: 13.50

Here, int a is promoted to float before addition.


3. Explicit Type Conversion (Type Casting)

  • Done manually by the programmer using type casting operator:

(type) expression
  • Example: Convert float to int

#include <stdio.h>

int main() {
float x = 3.99;
int y;

y = (int)x; // explicit conversion
printf("x = %.2f, y = %d\n", x, y);

return 0;
}

Output:

x = 3.99, y = 3

Note: Type casting truncates the decimal part.


4. Type Conversion in Expressions

  • Mixed data types in expressions are promoted to the larger type automatically.

#include <stdio.h>

int main() {
int a = 5;
double b = 2.0;
double result;

result = a / b; // 'a' promoted to double
printf("Result: %.2lf\n", result);

return 0;
}

Output:

Result: 2.50
  • Without type conversion:

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

Integer division truncates the result; type casting can fix this:

result = (float)a / b; // result = 2.5

5. Key Points

  1. Implicit conversion: automatic, usually safe, promotes smaller type to larger type.

  2. Explicit conversion: manual, can lose data (e.g., float → int).

  3. Use casting to ensure correct results in mixed-type expressions.

  4. Common casting: int, float, double, char.


6. Combined Example

#include <stdio.h>

int main() {
int a = 10, b = 4;
float result;

// Implicit conversion
result = a + 2.5; // a promoted to float
printf("Implicit Result: %.2f\n", result);

// Explicit conversion
result = (float)a / b; // cast int to float for correct division
printf("Explicit Result: %.2f\n", result);

return 0;
}

Output:

Implicit Result: 12.50
Explicit Result: 2.50

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *