Type Conversion with Example

Subject: PPS (Programming for Problem Solving)

Contributed By: Sanjay

Created At: February 3, 2025

Question:


What is type conversion? Explain Explicit and Implicit type conversion , and give example program.

Explanation Video:

Custom Image

Explanation:

Type Conversion:

Type Conversion is the process of converting one data type into another. It allows you to perform operations on variables of different types. In C, there are two types of type conversion:

  1. Implicit Type Conversion (Automatic Conversion)

  2. Explicit Type Conversion (Manual Conversion)

I. Implicit Type Conversion

Implicit Type Conversion is performed automatically by the compiler when a value of one data type is assigned to a variable of another type. This conversion occurs when the compiler determines that it's safe to convert the data from one type to another without loss of information.

Example: Converting an int to a float because a float can store larger or decimal values.


Example Program:

#include <stdio.h>

int main() {

   int a = 5;

   float b;

   // Implicit conversion: 'a' is automatically converted to float and assigned to 'b'

   b = a;  // a is converted to float automatically

   printf("Integer value: %d\n", a);  // Prints: Integer value: 5

   printf("Converted float value: %.2f\n", b);  // Prints: Converted float value: 5.00

   return 0;

}

In this example, the int variable a is implicitly converted to a float when assigned to b.

II. Explicit Type Conversion

Explicit Type Conversion (also called type casting) is done manually by the programmer. The programmer tells the compiler to convert a value from one type to another using a cast operator.

  • Syntax:
  • (target_type) value

Example: Converting a float to an int (which may result in data loss).

Example Program:

#include <stdio.h>

int main() {

   float x = 5.75;

   int y;

   // Explicit conversion (type casting): 'x' is manually converted to int

   y = (int) x;  // Explicit conversion, fractional part is discarded

   printf("Original float value: %.2f\n", x);  // Prints: Original float value: 5.75

   printf("Converted integer value: %d\n", y);  // Prints: Converted integer value: 5

   return 0;

}

In this example, the float variable x is explicitly converted to an int by the programmer, and the fractional part is discarded.

  1. Implicit Type Conversion:

    • Done automatically by the compiler.

    • Happens when a value of a smaller data type (like int) is assigned to a larger data type (like float).

    • No data loss occurs.

  2. Explicit Type Conversion:

    • Done manually by the programmer.

    • Uses type casting (e.g., (int) x).

    • May result in data loss (e.g., converting a float to int).

Share this Article & Support Us:
Status
printf('Loading...');