TYPE CASTING:
Okay !!! Till now we have learnt some programming techniques. Now let's C how C compiler will perform operations related to datatypes.
- We can determine expression 5+6 will give a value 11 , which is an integer, but what if we have one float operand and one int operand as shown.
5.3 + 6;
- In above expression 5.3 is float and 6 is int, C first converts 6 to float that is 6.0 and then the sum is calculated.
- Now 5.3+6.0 is 11.3. Well this is called implicit type casting.
- We have two types of type casting 1) Implicit 2) Explicit
IMPLICIT TYPE CASTING:
Implicit type casting is further divided into two types
i)Direct and
ii) Assignment
DIRECT TYPECASTING:
- The expression 5.3 + 6 is an example of direct typecasting. Where compiler is converting 6 to float internally.
- Let’s have another example 7/5, where the result should be 1.4 but we get 1 because 7 and 5 are both integer values and due to implicit automatic typecasting we get the result as 1.
- Not to get such an erroneous result we convert the expression as shown below.
7.0/5 or 7/5.0 now the result is 1.4.
- Either one is true because if one is float all other variables are converted into float and the result is obtained is also float.
ASSIGNMENT TYPECASTING:
- In above example we came to know about implicit automatic typecasting(direct typecasting) but what if we have the expression as shown below
int f;
f=7.0/5 what is stored in f ? 1.4 ?
- Well the answer is no, because the compiler converts the data type at RHS of the assignment operator to data type at the LHS of the assignment operator. Thus in above example variable f is a int type and thus in the value 1.4, .4 is truncated and only 1 is stored in f.
Program:
/* Assignment Typecasting */
#include<stdio.h>
int main()
{
int i;
float f;
i=7.0/5;
f=7.0/5;
printf("\nThe value in i is :\t%d",i);
printf("\nThe value in f is :\t%f",f);
return 0;
}
Output:
The value in i is : 1
The value in f is : 1.400000
EXPLICIT TYPECASTING:
- We have seen that to obtain the accurate result in 7/5 we are converting one of the variable to float type. We can also use the expression below to obtain the same result.
Example:
float y;
y=(float)7/5;
- Now 1.4 is stored in y, here we are explicitly converting 7 to float thus other operand i.e. 5 is also converted to float and obtained result is stored in y.
Program:
/* Explicit type casting program */
#include<stdio.h>
main()
{
int i;
float f;
i=(float)7/5;
f=(float)7/5;
printf("\nThe value in i is :\t%d",i);
printf("\nThe value in f is :\t%f",f);
return 0;
}
Output:
The value in i is : 1
The value in f is : 1.400000
NOTE: Be careful with format specifiers if you are using %d to print a float value a unknown value will be printed.
No comments:
Post a Comment