Type Casting In C Language

aimtocode

Type Casting Definition

Generally, Type Casting is the procedure or a way to converting from one data type to another data type by using type casting method.

Type Casting Rules

  • Type casting can be used to convert lower datatypes to higher datatypes and viceversa e.g. int (2 bytes) to float (4 bytes).
  • The type name to which conversion is to be done is placed in a closed parenthesis just before the variable. e.g. if a float variable 'f' has a value 7.5, it can be converted into an integer type using (int)f.

syntax:


  (type_name) expression

example:



Output:

 i value is 90
 x value is 90.000000
 i value is 65

Type Casting Lower Datatype Conversion



Output:


 The value of c = 1.500000

Note: Variables a, b, c belongs to integer data type, where actual result will be in float. Thus, we are typecasting the data type of variable 'c' from an intfloat.

Implicit type casting

Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable.

Implicit type conversion happens automatically when a value is copied to its compatible data type.

Example:



Output:

 10
 10

Converting Character to Int

Consider the example of adding a character decoded in ASCII with an integer:



Output:


  Value of sum : 108

Explicit type casting

In implicit type conversion, the data type is converted automatically.

Syntax:

(data_type)expression;

Example:



Output:

 Value of a is 1.200000
 Value of b is 2

Example 2:



Output:

  n = 90, k = 54
  ch = F  s = 70
  R = 5.200000 P = 5
  M = 3.333333, m =3							
aimtocode