Type Casting

Type Casting


Converting one type of data into another type of data is called as type conversion. What happens when we write an expression that involves two different types of data, such as multiplying an integer and a floating point number? To perform these evaluations, one of the types must be converted.

There are two types of Type conversions:

1) Implicit type conversion

2) Explicit type conversion

Implicit type conversion:

When the types of the two operands in a binary expression are different, C automatically converts one type to another. This is known as implicit type conversion.

Example:

char c = „A‟;
int i = 1234;
long double d = 3458.0004;
i = c; // since i is integer type C automatically converts c=‟A‟ as c = 65 and then assigns 65 to i
d = i; // since d is long double, value of i is converted to 1234.0 and it is assigned to d.
X = d + i; // X = double + int is converted to X = double + double, since d and i are of two different types(int is promoted to long double type), therefore result of X is 4692.0004(3458.0004 + 1234.0)


Explicit type conversion:

Rather than let the compiler implicitly convert data, we can convert data from one type to another ours self using explicit type conversion. Explicit type conversion uses the unary cast operator, which has a precedence of 14.

To cast data from one type to another, we specify the new type in parentheses before the value we want to be converted.

For example,

To convert an integer A to a float, we code the expression as given below

(float) A

One use of the cast operator is to ensure that the result of a divide is a real number. For example, if we calculated ratio of girls and boys (both are integer values) in a class without a cast operator, then the result would be an integer value. So to force the result in fractional form, we cast calculation as shown below.

Ratio = (float) No_of_Girls / No_of_Boys;

Or

Ratio = No_of_Girls / (float) No_of_Boys;



Qus. 1 : which is used to converts an expression to a specified data type

  1. Logical Operator
  2. Conditional Operator
  3. typecast
  4. Ternary

Programs

Program to Convert Days into week and days Format

View Solution


Program to Convert Days into Month, Week and Days Format

View Solution


C Program to Find ASCII Value of a Character

View Solution


C Program to Print an Integer

View Solution


C Program to Compute Quotient and Remainder

View Solution


C Program to Find the Size of int float double and char

View Solution


C Program to Swap Two Numbers

View Solution


C program to Swap Numbers Without Using Temporary Variables

View Solution


C Program to Check Odd or Even Using the Ternary Operator

View Solution


Latest Current Affairs 2025 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Online MBA 2 years Online MCA Online BCA Best Website and Software Company in Allahabad