Thursday, January 14, 2016

Implicit and Explicit Type Casting

Type casting can either be performed by the compiler automatically or user can specify them using the syntax described above. Former type is called implicit type casting and the latter is called explicit type casting.
What is implicit type casting/ implicit type conversion?
We've explained the explicit type conversion in the above paragraphs. Now lets's take a look at how implicit type conversion works. In implicit type conversion compiler takes care of the casting without requiring the programmer to specify them explicitly. For example in the program given below, compiler converts the sum of two float numbers to an int.
  1. ##include <stdio.h>
  2.  
  3. int main()
  4. {
  5. float value1 = 2.2;
  6. float value2 = 3.3;
  7. int result;
  8.  
  9. result = value1 + value2;
  10. printf("Result : %d", result);
  11. return 0;
  12. }
  13.  
  14. Output:
  15. Result : 5
Note: Though compiler performs implicit type casting, it's always recommended to specify the conversion explicitly because this improves the code readability and makes it easier to port to other platform.

No comments: