C Type Conversion

Type conversion, also known as type casting, is the process of converting a value from one data type to another data type. In C programming language, there are two types of type conversions:

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

Implicit type conversion, also known as coercion, is an automatic type conversion that is performed by the compiler. It occurs when an expression of one data type is used in a context where another data type is expected. In this case, the value is converted to the expected data type automatically by the compiler.

Example:

int num1 = 10;
float num2 = 3.14;
float result = num1 + num2;  // implicit type conversion of num1 to float

In the above example, the value of num1 is implicitly converted to a float type to perform the addition operation with num2.

Explicit Type Conversion

Explicit type conversion, also known as type casting, is a manual type conversion that is performed by the programmer. It allows the programmer to convert a value of one data type to another data type explicitly.

Example:

int num1 = 10;
float num2 = 3.14;
int result = (int)(num1 + num2);  // explicit type conversion of the result to int

 

In the above example, the value of num1 is added to num2, which results in a float value. Then, the result is explicitly converted to an integer type using the (int) casting operator.

Type Conversion Rules

In C programming language, the following rules apply for type conversion:

  1. The lower data type is automatically promoted to the higher data type in an expression.
  2. The data types of the operands in an expression must be compatible with the operator used.
  3. When an integer and a floating-point value are used in an expression, the integer value is automatically converted to a floating-point value.
  4. When a value of a larger data type is assigned to a variable of a smaller data type, the value is truncated to fit into the smaller data type.

It is important to understand the rules of type conversion in C programming language to avoid unexpected results in your programs.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

48627