Type casting & Type Conversion | Bkhakt Kavi Narsinh Mehta University Junagadh | BKNMU



 Type Conversion:

Type conversion is the process of converting one data type into another. In C, it can happen implicitly (automatically by the compiler) or explicitly (manually by the programmer).


Implicit Type Conversion:

This occurs when the compiler automatically converts one type to another without any explicit instruction from the programmer. For example:

int num_int = 10; float num_float = num_int; // Implicit conversion from int to float


Here, the int value 10 is implicitly converted to a float when assigned to num_float. This is allowed because a float can accommodate an integer value without loss of precision.

Explicit Type Conversion (Type Casting):

Type casting is the explicit conversion of a variable from one data type to another. It's done by placing the desired data type in parentheses before the variable to be converted. For example:


float num_float = 10.5; int num_int = (int)num_float; // Explicit conversion from float to int



In this case, the value in num_float is explicitly cast to an int type using (int). This operation results in num_int having the integer part of the num_float, effectively truncating the decimal part.


Here's a step-by-step breakdown:

Declare Variables:

float num_float = 10.5; int num_int;


Explicit Type Conversion:

num_int = (int)num_float;


Explanation:
  • (int) tells the compiler to treat num_float as an int.
  • The decimal part of num_float is discarded, and only the integer part is assigned to num_int.
  • num_int now contains the value 10.

Remember:

  • Type casting can lead to loss of data or precision, especially when converting from a larger data type to a smaller one.
  • It's important to be cautious when performing type casting to avoid unintended consequences like data loss.


Post a Comment

Thanks for comment.

Previous Post Next Post