What is type conversion in C language - Type conversion kya hota hai - What is type conversion in programming language - Type conversion

What is type conversion in C language?

Type conversion, also known as "typecasting" or "type coercion," is changing an expression from one data type to another in the C programming language. This allows you to use variables or values of one data type in a context that expects a different data type. Type conversion is essential to ensure compatibility and correctness in expressions and operations involving different data types.
 
In C, type conversion can be categorized into two main types:
 
1. Implicit Type Conversion (Coercion):   

  • Implicit type conversion, also known as "coercion" or "automatic type conversion," is performed by the compiler automatically without the programmer's explicit request.
  • This conversion occurs when an expression of one data type is used in a context where another data type is expected.
  • The compiler performs the conversion to ensure that the types are compatible.
 
   Example of implicit type conversion:
  
   int a = 10;
   double b = 5.5;
   double result = a + b; // Implicitly converting 'a' to a double before the addition

 
2. Explicit Type Conversion (Casting):
  • Explicit type conversion, also known as "casting," is a manual conversion performed by the programmer using casting operators.
  • The programmer explicitly specifies the desired type to which the value or expression should be converted.
  • Explicit type conversion is valid when you want to override the default behaviour of implicit type conversion.
 
   Example of explicit type conversion:
  
   int x = 10;
   double y = 5.5;
   int sum = (int)(x + y); // Explicitly casting the result to an integer
 
In C, there are two types of explicit type casting:
 
- C-style Casting:

  •  This involves using the syntax `(type) expression` to perform the conversion.
  •  For example: `(int) 3.14` or `(float) 10`.
 
- Type Conversion Functions:  

  • Functions like `int()`, `float()`, `double()`, etc., can be used for explicit type conversion.
  • For example: `int(3.14)` or `float(10)`.
 
It's important to use type conversion carefully to prevent unintended loss of precision or data truncation. Additionally, consider the implications of type conversion on the behaviour and correctness of your program.

Comments