Followers

Friday, November 17, 2023

Explicit and Implicit type conversion in C

 



In C, type conversions can be classified into two categories: explicit (also known as type casting) and implicit (automatic or type coercion) type conversions.

1. Explicit Type Conversion:
Explicit type conversion involves the programmer explicitly specifying the type conversion using casting operators. This is done when there is a need to convert a value from one data type to another, and the compiler may not perform the conversion automatically.

Example:

#include <stdio.h>

int main() {
    double pi = 3.14159;
    int intPi;

    // Explicit type conversion using casting operator
    intPi = (int)pi;

    printf("Double pi: %f\n", pi);
    printf("Integer intPi: %d\n", intPi);

    return 0;
}

In this example, the value of pi is explicitly cast to an integer using (int)pi. This ensures that the fractional part is truncated, and only the integer portion is stored in intPi.

2. Implicit Type Conversion:
Implicit type conversion occurs automatically by the compiler when it is safe and does not result in data loss. It is also known as type coercion.

Example:

#include <stdio.h>

int main() {
    int numInt = 10;
    float numFloat;

    // Implicit type conversion from int to float
    numFloat = numInt;

    printf("Integer numInt: %d\n", numInt);
    printf("Float numFloat: %f\n", numFloat);

    return 0;
}

In this example, the value of numInt is implicitly converted to a floating-point number when assigned to numFloat. The conversion is done automatically by the compiler.

Summary:

Explicit Type Conversion: Programmer manually specifies the type conversion using casting operators. (type)value syntax is used for explicit casting.

Implicit Type Conversion: Compiler automatically performs the type conversion when it is safe, and no explicit casting is needed.

It's important to be cautious with explicit type conversions, as they might result in loss of data or unexpected behavior if not done carefully. Implicit type conversions, on the other hand, are handled by the compiler, and the programmer should be aware of the rules governing these conversions to avoid unintended consequences.

No comments:

Post a Comment