GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

Type conversion in C

Type conversion says converting one datatype to another. There will be some situations in programming where we would want to convert from one datatype to another. It is also called as type casting.

Say for example, we want to calculate 2/3, which is 0.67 mathematically and 0 programmatically, so we would want either 2 or 3 to convert to double number.

There are two types of “type conversion”

  1. Implicit type conversion.
  2. Explicit type conversion.

You may watch the video posted at the end of this page.

Implicit type conversion

The implicit type conversion is automatically done by the compiler. 

Example 1:

int a = 2.3; 

we are trying to store double number in integer, which is not possible, and the compiler converts this to an integer value by truncating the decimal point.

Therefore, a = 2;

implicit conversion

Example 2:

int y = ‘A’;

We see that the RHS is character and the LHS is an integer. The character will be converted to an integer and the ASCII value of ‘A’, which is 65, will be stored. Therefore, y = 65

implicit conversion

Example 3:

double m = 3;

We see that the RHS value is integer, and the LHS is double, integer is upgraded to double and 3.0 will be stored in m.

implicit conversion

Explicit type conversion

The explicit type conversion is the forceful conversion done by the programmer. It is not done by the compiler.

General Syntax:
variable=(data_type)variable_name or value;

Example 1:

int a = 2;

int b  = 3;

double c = a/b;  (The value of var, c, will be 0, since int/int = int)

To get the value, 0.67, we need to convert either ‘a’ or ‘b’ or both to double. But there might be situations where we don’t want to change the datatype of the variables. That is where the explicit type conversion comes into play.

Explicit type conversion is converting one datatype to another datatype momentarily.

Therefore, we write

double d = (double)a/b;

The value of d will be 0.67.

The variable ‘a’ will be converted to double only where it is written as (double)a, rest at all the places the datatype of ‘a’ will be an integer.

Scroll to Top