Type Casting in C ? Types of Type Casting in C

 

Type Casting in C

Typecasting allows us to convert one data type into other. In C language, we use cast operator for typecasting which is denoted by (type).

Type Casting in C


syntax :

c
(type) expression

Types of Type Casting in C 

  1. Implicit Type Casting (Type Coercion): Implicit type casting is done automatically by the C compiler when you perform operations involving different data types. The compiler converts one or more operands to a common data type before performing the operation. This is also known as "type coercion." For example:

    c
    int a = 5; double b = 2.5; double result = a + b; // Implicit type casting of 'a' to double
    In the above example, the integer a is implicitly cast to a double before performing the addition operation.
  2. Explicit Type Casting: Explicit type casting allows you to manually convert a value from one data type to another by using casting operators. 

    Here's an example of explicit type casting using C-style casting:

    c
    double b = 2.5; int a = (int)b; // Explicit type casting of 'b' to int
    In this example, the value of b is explicitly cast to an integer, resulting in the value 2 being assigned to a.It's important to note that type casting should be used with caution because it can lead to data loss or unexpected behavior if not done correctly. You should be aware of the potential loss of data when converting from a wider data type to a narrower data type.
  3. Here are a few more examples of explicit type casting:

    c
    double pi = 3.14159; int truncatedPi = (int)pi; // Explicitly cast double to int, truncating the decimal part int x = 65; char ch = (char)x; // Explicitly cast int to char, converting the ASCII value to a character
    In the above examples, explicit type casting is used to convert a double to an int and an int to a char.

Post a Comment

0 Comments