[go: up one dir, main page]

DEV Community

Sujith V S
Sujith V S

Posted on • Edited on

Type Conversion in C programming.

In C programming, type conversion refers to the process of changing the data type of a variable. There are two main types of type conversions:

Implicit Type Conversion

This is done automatically by the compiler when necessary. It occurs when the compiler needs to convert a data type to another type to perform an operation or function call.

Datatype hierarchy plays a crucial role in converting one datatype to another datatype. In implicit type conversion, data types lower in the hierarchy are automatically converted to those higher in the hierarchy.

Datatype hierarchy
long double
double
float
long
int
short
char

Example:

int main() {

    char a = '5'; //the character value is converted automatically to its ascii value.
    int b = 9;

    int result = a + b;

    printf("%d", result);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

In the above code a is assigned by '5', which is a character value. The char datatype is lower than the int datatype in the hierarchical order. Therefore, if we try to add char value '5' and int value 9, then the char value '5' will be automatically converted to its ASCII value. The output of the above code is 62.

What happens if we try to assign double datatype to int type variable?

int main() {

    int a = 5.67;

    printf("%d", a);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

In the above code, the double datatype(higher in hierarchy)
is converted to int datatype(lower in hierarchy). This is because, during the assignment operation the datatype at the right side of the assignment is always converted to the datatype at the left.

Explicit Type Conversion

This is done manually by the programmer using a cast operator. Cast operators allow you to explicitly tell the compiler what data type you want to convert a variable to.
Here is the syntax for explicit type conversion: (target_type) expression;

Example:

float number1 = (float) 10; // Convert an integer to a float
int number2 = (int) 3.14; // Convert a float to an integer
char ch = (char) 65; // Convert an integer to a character
Enter fullscreen mode Exit fullscreen mode

Top comments (0)