C Type Casting

Converting any variable datatype into another datatype is called as type casting.
It is best to do type casting to avoid data loss.

Syntax for type casting

Two types of typecasting are:

  1. implicit typecasting
  2. explicit typecasting

Implicit typecasting:

Implicit typecasting is handled automatically by the compiler. Following example shows how implicit typecasting works-

Output: 2.0

The actual output of a/b is 2.5. But in C language int/int (integer/integer) will give an integer as an output.
So 0.5 get truncated. Therefore output is 2.
Value 2 is stored in c variable as a float number i.e c = 2.0 since c is a variable of type float. In this way compiler does this typecasting implicitly.

Explicit typecasting:

Explicit typecasting is done explicitly done by the programmer. Following example shows the explicit typecasting done by user-

Output: 2.5

The ‘(float)a’ convert ‘a’ into float value before division. So temporary, for time being, ‘int a’ gets converted into a float for this expressions only.
Here ‘float/int’ will give value in floating number, therefore, numbers won’t get truncated.
Therefore output is 2.5.

Program illustrate typecasting:

Write a program to accept marks of 5 subjects from the user and calculate their average. Use implicit and explicit typecasting.

Output:

 

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.