Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

Type Conversion:

Type Conversion is also known as Typecasting. Typecasting is converting one data type into another one. 

There are two types of Type Conversion:

1. Implicit Type Conversion:

 Implicit Type casting means losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the value stored in the variable. Implicit type Conversion in C happens automatically when a value is copied to its compatible data type.

Example:

#include <stdio.h>
int main() {
    int integerNumber = 10;
    double doubleNumber;
    // Implicit conversion (int to double)
    doubleNumber = integerNumber;
    // Displaying values
    printf(“Integer Number: %dn”, integerNumber);
    printf(“Double Number: %fn”, doubleNumber);
    return 0;
}

In this example, the integer variable integerNumber is implicitly converted to a double when assigned to doubleNumber.

Output:

Integer Number: 10
Double Number: 10.000000

2. Explicit Type Conversion:

Explicit type conversion, also known as “casting,” is performed by the programmer and involves specifying the desired type using casting operators. This is useful when you want to enforce a specific type conversion or when converting from a “larger” type to a “smaller” one, which may result in data loss.

Example:

#include <stdio.h>

int main() {
    double doubleNumber = 3.14;
    int integerNumber;

    // Explicit conversion (double to int)
    integerNumber = (int)doubleNumber;

    // Displaying values
    printf(“Double Number: %fn”, doubleNumber);
    printf(“Integer Number: %dn”, integerNumber);

    return 0;}

In this example, the double variable doubleNumber is explicitly cast to an int when assigned to integerNumber. Note that the fractional part is truncated.

Output:

Double Number: 3.140000
Integer Number: 3