How does automatic typecasting work in Fortran?
Purpose is determined by Fortran 2008 Section 7.2. It should be noted that Cl. 7.2.1.3 Clause 8:
For an internal assignment operator, where the variable has a numeric type, the expression can have different numeric values โโof type or kind type, in which case the value of expr is converted into a parameter of the type and type of the type of the variable in accordance with the rules of Table 7.9.
Table 7.9: Numeric Conversion and the Assignment Operator
Type of variable Value Assigned integer INT(expr , KIND = KIND (variable)) real REAL(expr , KIND = KIND (variable)) complex CMPLX(expr , KIND = KIND (variable))
This means that any expression ( expr
) will be implicitly converted to the type and kind of the variable to which it is assigned. For character types, derived types and everything else, see the Standard.
Also note that Fortran only performs such conversions during assignment and initialization, not for contexts such as procedure calls. For example, consider this procedure:
subroutine sub1(a)
implicit none
integer :: a
print *, a
end subroutine
This procedure has a dummy integer argument. You cannot, for example, do this:
call sub1(1.d0)
because it results in a type mismatch between the actual and the dummy arguments.
You can, however, do this:
integer :: a
a = 1.d0 !implicitly interpreted as: a = INT(1.d0, kind=kind(a))
call sub1(a)
because implicit conversion is defined for assignment.
The only documented extension to the standard for implicit type conversion in gfortran (5.1.0) is boolean and integer types at assignment time.
- Boolean
.true.
converts to integer1
- Boolean
.false.
converts to integer0
- Integer is
0
converted to.false.
- Any other integer is converted to
.true.
Note that if you can get by without the legacy extensions, don't use them. Using them means that your program is not standard Fortran, and therefore any compiler could reject it as incorrect. These extensions are intended to enable legacy code to compile with modern compilers, not for use in new code.
source to share