Type Casting in C Language PDF
Type Casting in C Language PDF
NET
Type casting is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then
you can type cast long to int. You can convert values from one type to another
explicitly using the cast operator.
New data type should be mentioned before the variable name or value in brackets
which to be typecast.
1 #include <stdio.h>
2 int main ()
3 {
4 float x;
5 x = (float) 7/5;
6 printf("%f",x);
7 }
Output:
1.400000
Here, It is best practice to convert lower data type to higher data type to avoid
data loss.
Data will be truncated when higher data type is converted to lower. For example,
if float is converted to int, data which is present after decimal point will be lost.
Types of typecasting in C
S.No Types of typecasting in C Programming
1 Implicit Conversion
2 Explicit Conversion
1. Implicit conversion
Implicit conversions do not required any operator for converted . They are
automatically performed when a value is copied to a compatible type in program
.
Here, the value of a has been promoted from int to double and we have not had
to specify any type-casting operator. This is known as a standard conversion.
Example :-
1 #include<stdio.h>
2 #include<conio.h>
3 void main()
4 {
5 int i=20;
TYPECASTIN IN C LANGUAGE – BY WWW.IMPROGRAMMER.NET
6 double p;
7 clrscr();
8
9 p=i; // implicit conversion
10
11 printf("implicit value is %d",p);
12
13 getch();
14 }
Output :-
implicit value is 20.
2. Explicit conversion
They are not automatically performed when a value is copied to a compatible type
in program.
Example :-
1 #include<stdio.h>
2 #include<conio.h>
3 void main()
4 {
5 int i=20;
6 short p;
7 clrscr();
8
TYPECASTIN IN C LANGUAGE – BY WWW.IMPROGRAMMER.NET
Output :-
Explicit value is 20.
The usual arithmetic conversions are implicitly performed to cast their values in
a common type,C uses the rule that, in all expressions except assignments, any
implicit type conversions made from a lower size type to a higher size type as
shown below:
TYPECASTIN IN C LANGUAGE – BY WWW.IMPROGRAMMER.NET
We are recently taking a survey from different programmers who are available
in google plus social media. We did a survey for type casting in c language.