AsegGasiaBlog

C Programming - Operators - Type Cast Operator

Type Cast Operator

Cast operator can be used to explicitly convert the value of an expression to a different data type

Two Types of Cast

  • Implicit Cast
  • Explicit cast
Implicit Cast -

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.

Explicit Cast -

Explicit type conversion is a type conversion which is explicitly defined within a program 

(instead of being done by a compiler for implicit type conversion).

  • Lower DataType to Higher DataType are converted implicitly
  • Higher DataType to Lower DataType are converted explicitly

Example :


#include <stdio.h>

int main()
{
    int i   = 10;
    float f = 3.147;

    printf("The integer is: %d\n", i);
    printf("The float is:   %f\n", f);

    //implicit conversion
    f = i;
    printf("Implicit conversion int to float :   %f\n", f);

    //explicit conversion
    i = (int) f;
    printf("Explicit conversion float to int :   %d\n", i);

    return 0;
}

Output :

 The integer is: 10
 The float is:   3.147000
 Implicit conversion int to float :   10.000000
 Explicit conversion float to int :   10

Popular Posts