Type Casting

What is meant by type casting? Explain implicit and explicit type casting.

Type Casting
The process of converting the data type of a value during execution is known as type casting. Type casting can be performed in two ways:

  1. Implicit type casting
  2. Explicit type casting

Implicit Type Casting
Implicit type casting is performed automatically by the C compiler. The operands in arithmetic operation must be of similar types. If the data types of operands are different, the value with lower data type is converted into the higher data type. For example, x is an integer variable and y is a long variable, so in any calculation the data type of the value of x will be converted into long during the evaluation of any expression.

Explicit Type Casting
Explicit casting is performed by programmer. It is performed by using cast operator. The cast operator tells the computer to convert the data type of a value. Suppose x and y are two float variables, following expression is executed (x%y). It will generate an error because modulus operator cannot work with float variables. It only works with integers. So the values of x and y will be converted into integer by following expression (int) x % (int) y.