Wednesday, January 13, 2016

C Type Casting with examples - float to int / int to char / int to long

The value of a variable or expression can be converted to another data type if desired. It is called type casting or type conversion. If you have a variable of data type long and you want to assign it to an int type variable, type casting can be used for that purpose. To type cast a variable or expression it must be preceded by the desired datatype as follows.
(data type) expression;

Why do we need type casting?

Type casting would be pretty handy when your inputs to an operation is of a particular type and you need more precision in the output. Let's see the use of type casting through a simple example
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. int value1 = 10, value2 = 3;
  6. float result;
  7. result = value1 / value2;
  8. printf("Result without type casting: %f", result);
  9. return 0;
  10. }
  11.  
  12. Output:
  13. Result without type casting: 3.000000
In the above example we assign the result of division operation to float type variable result. The result is supposed to be 3.333333. But we get the result as 3.000000. Can you think why? Because the two operands of the expression, value1 and value2 are of int type. This causes compiler to treat the result also as integer; that means, it will ignore the decimal part of the result and store the integer result in float variable.



So how do you get the result with correct precision? Just cast the type of expression to the type you need! You can see the solution below.

  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5. int value1 = 10, value2 = 3;
  6. float result;
  7.  
  8. result = (float)value1 / value2;
  9. printf("Result with type casting: %f", result);
  10. return 0;
  11. }
  12.  
  13. Output:
  14. Result with type casting: 3.333333
One important thing to notice here is that, type casting has more precedence than the divide operation (/). At first, value1 will be converted to float type and then division operation is performed on the float variable.

No comments: