C Type Conversion

C Type Conversion (Casting)

Sometimes, you need to convert the value of one data type to another data type. This process is known as type conversion or type casting.

In C, there are two main types of conversion:

  1. Implicit Conversion (automatically done by the compiler)
  2. Explicit Conversion (manually done by the programmer)

1. Implicit Conversion (Automatic)

Implicit conversion happens automatically when you assign a value of one type to a variable of another type. The compiler handles it for you, typically promoting smaller types to larger types to avoid data loss.

For example, if you assign an int to a float, the compiler automatically converts the integer to a floating-point number.

Implicit Conversion Example

#include <stdio.h>

int main() { // Automatic conversion: int to float float myFloat = 9;

printf("Value of myFloat: %f\n", myFloat); // Outputs 9.000000

return 0; }

Risk of Data Loss

Implicit conversion can be dangerous if you assign a larger type to a smaller type (like a float to an int). The compiler will truncate (cut off) the decimal part, leading to data loss.


2. Explicit Conversion (Manual Casting)

Explicit conversion is when you manually change a value from one type to another. You do this by placing the desired type in parentheses () directly in front of the value or variable you want to convert.

This is highly recommended because it makes your intentions clear to anyone reading the code and gives you precise control over the conversion process.

Syntax:

(type) value;

Explicit Casting Example

#include <stdio.h>

int main() { int num1 = 5; int num2 = 2; float sum;

// With explicit casting, we treat num1 as a float before division sum = (float)num1 / num2;

printf("Result of division: %f\n", sum); // Outputs 2.500000

return 0; }


Exercise

?

What is the syntax for explicit type conversion in C?