Type Casting Operator in C Programming Language

Notes:

Type casting operator in C programming language:
- Converting one type of data value to another type is called as type casting.

There are 2 types of type casting:
Implicit type casting (Coercion): Done by C compiler
Explicit type casting (Conversion): Done by programmers

Implicit type casting:
While evaluating an expression; if required C compiler automatically converts one type of data value to another type implicitly; which is called as implicit type casting.

Note: While performing implicit type casting
- smaller data type values are automatically converted to larger data type values
- non precision type data values are automatically converted to precision type data values

Ex:
printf("%d\n", 'A' + 1); // 65 + 1 = 66
printf("%f\n", 2 + 4.5); // 2.0 + 4.5 = 6.5

Explicit type casting:
While evaluating an expression; if required, we programmers can also convert one type of data value to another type explicitly; which is called as explicit type casting.

For explicit type casting, we use type casting operator in C

Syntax:
(data_type) operand
- it converts the given operand to a data type specified in the pair of parenthesis

Ex:
printf("%f\n", 5 /2); // 0.000000
printf("%f\n", 5 / (float)2); // 5.0 / 2.0 = 2.5
printf("%d\n", 2 + (int)4.5); // 2 + 4 = 6

Example Code:

#include <stdio.h>
int main()
{
/* implicit type casting */

printf("%d\n",'A' + 1); // 65 + 1 = 66
printf("%f\n",2 + 4.5); // 2.0 + 4.5 = 6.5

/* explicit type casting */
printf("%f\n",5/2); // 0.000000
printf("%d\n",5/2); // int / int = int 5 / 2 =2
printf("%f\n",5/(float)2); // 5.0 / 2.0 = 2.5 float /float = float
printf("%f\n",(float)5/2); // 5.0 / 2.0 = 2.5 float /float = float
printf("%d\n", 2 + (int)4.5); // 2 + 4 = 6

return 0;
}