C Typecasting

C Typecasting – Converting Between Data Types

In C, typecasting is the process of converting one data type to another. Typecasting can be either implicit (automatic) or explicit (manual). It is essential to understand how to properly cast types to ensure the correct behavior in your programs.

๐Ÿ”น What is Typecasting?

Typecasting allows you to convert variables from one data type to another. It can be useful when you need to perform operations on variables of different data types or when you want to store a value in a specific type of variable.

๐Ÿ”น Implicit Typecasting (Automatic)

Implicit typecasting, also known as automatic type conversion, is done by the compiler when you assign a value of one data type to a variable of another data type. The compiler automatically converts the data type to the larger one to prevent data loss.

๐Ÿ“ Example 1: Implicit Typecasting

In this example, an integer is automatically converted to a float during the assignment.

#include <stdio.h>

int main() {
    int integer = 5;
    float floating_point;

    floating_point = integer;  // Implicit typecasting from int to float
    printf("The float value is: %.2f\n", floating_point);

    return 0;
}

Try It Now

๐Ÿ”น Explicit Typecasting (Manual)

Explicit typecasting, also known as type conversion, is performed by the programmer. It allows you to manually convert a value from one data type to another using the cast operator.

๐Ÿ“ Example 2: Explicit Typecasting

Here, we manually convert a float to an integer using explicit typecasting.

#include <stdio.h>

int main() {
    float floating_point = 5.75;
    int integer;

    integer = (int)floating_point;  // Explicit typecasting from float to int
    printf("The integer value is: %d\n", integer);

    return 0;
}

Try It Now

๐Ÿ”น Key Differences Between Implicit and Explicit Typecasting

  • Implicit typecasting is performed automatically by the compiler when converting from a smaller data type to a larger one (e.g., int to float).
  • Explicit typecasting is performed manually by the programmer when converting from a larger data type to a smaller one (e.g., float to int).
  • Implicit typecasting does not lose data, while explicit typecasting may result in data loss (e.g., truncating a float when converting it to an integer).

๐Ÿ“ Practice Time!

Try modifying the typecasting examples and experiment with different data types to understand how implicit and explicit typecasting work in C!