Type Casting in C

Type casting in C refers to converting a variable from one data type to another. It is used when you want to perform operations between different data types or when a specific data type is required by a function. C supports both implicit and explicit type casting.

1. Types of Type Casting in C

There are two main types of type casting in C:

2. Implicit Type Casting

Implicit type casting, also known as automatic type conversion, occurs when the compiler automatically converts one data type to another. This usually happens when a smaller data type is assigned to a larger data type (for example, an integer to a float).

Example of Implicit Type Casting:

                        
#include <stdio.h>
int main() 
{
  int a = 5;
  float b = a;  // Implicit type casting from int to float
  printf("Value of b: %.2f\n", b);
  return 0;
}
                        
                    

Output:

Value of b: 5.00

3. Explicit Type Casting

Explicit type casting, also known as manual type conversion, is performed by the programmer using the cast operator. It is necessary when converting a larger data type to a smaller data type (such as from a float to an int), as this may lead to data loss.

Syntax for Explicit Type Casting:

                        
type_name variable = (type_name) expression;
                        
                    

Example of Explicit Type Casting:

Example

                        
#include <stdio.h>
int main() 
{
  float a = 5.75;
  int b = (int) a;  // Explicit type casting from float to int
  printf("Value of b: %d\n", b);
  return 0;
}
                        
                    

Output

Value of b: 5

4. Important Points to Remember

5. Common Type Casting Operations