Expressions can be explicitly cast using the cast operator, a type bound in parentheses/round brackets, e.g. (int). In all cases, the conversion of one type to another must be done with caution and only when necessary.
Consider the example:
Here, a long type is being assigned to a int type (the assignment will truncate the value in long variable l). The compiler will automatically perform a type conversion from the type of the expression on the right of the assignment operator, to the type of the lvalue on the left of the operator. This is called an "implicit type conversion".
You should not use a cast in this expression. The compiler knows the types of both operands and will perform the intended operation. If you do use a cast, there is the potential for mistakes if the code is changed. For example, if you had:
The code will work in the same way, but, if in the future the type of i is changed to a long, for example, then the programmer must remember to adjust the cast, or remove it, otherwise the contents of l will continue to be truncated by the assignment.
Only use a cast in situations where the types the compiler will use are not the types that you would like it to use. For example, consider the result of a division assigned to a floating-point variable:
In this case, integer division is performed and the result is then converted to a float format. So if i contained seven and j contained two, the division will yield three and this will be implicitly converted to a float type (3.0) and then assigned to fl. If you wanted the division to be performed in a float format, then a cast is necessary:
For example, either i or j can be cast before the division. The result assigned to fl now be 3.5.
An explicit cast may suppress warnings that might otherwise have been produced. Checking the warnings in your code is a good way to find potential bugs.