Introduction
Type casting is used when you want to convert the value of a variable from one type to another. Suppose you want to print the value of a double data type in integer form. You can use type casting to do this. Type casting is done to cast an operator which is the name of the target data type in parentheses.
Program
#includemain() { double d1 = 123.56; \\ A int i1=456; \\ B printf("the value of d1 as int without cast operator %d\n",d1); \\ C printf("the value of d1 as int with cast operator %d\n",(int)d1); \\ D printf("the value of i1 as double without cast operator %f\n",i1); \\ E printf("the value of i1 as double with cast operator %f\n",(double)i1); \\ F i1 = 10; printf("effect of multiple unary operator %f\n",(double)++i1); \\ G i1 = 10; \\ H //printf("effect of multiple unary operator %f\n",(double) ++ -i1); error \\ I i1 = 10; printf("effect of multiple unary operator %f\n",(double)- ++i1);\\ J i1 = 10; \\ K printf("effect of multiple unary operator %f\n",(double)- -i1); \\ L i1 = 10; \\ M printf("effect of multiple unary operator %f\n",(double)-i1++); \\ N }
Explanation
-
Statement A defines variable d1 as double.
-
Statement B defines variable i1 as int.
-
Statement C tries to print the integer value of d1 using the placeholder %d. You will see that some random value is printed.
-
Statement D prints the value of d1 using a cast operator. You will see that it will print that value correctly.
-
Statements E and F print the values of i1 using a cast operator. These will print correctly as well.
-
Statements from G onwards give you the effects of multiple unary operators. A cast operator is also a unary operator.
-
Unary operators are associated from right to left, that is, the left unary operator is applied to the right value.
-
Statement G gives the effect of the cast operator double. The increment operator, in this case i1, is first incremented and then type casting is done.
-
If you do not comment out statement I you will get errors. This is because if unary +, − is included with the increment and decrement operator, it may introduce ambiguity. For example, +++i may be taken as unary + and increment operator ++, or it may be taken as increment operator ++ and unary +. Any such ambiguous expressions are not allowed in the language.
-
Statement J will not introduce any error because you put the space in this operator, which is used to resolve any ambiguity.
Points to Remember
-
Type casting is used when you want to convert the value of one data type to another.
-
Type casting does not change the actual value of the variable, but the resultant value may be put in temporary storage.
-
Type casting is done using a cast operator that is also a unary operator.
-
The unary operators are associated from right to left.
No comments:
Post a Comment