How does automatic typecasting (type conversion) work in Fortran?

5.9k views Asked by At

I am using gfortran compiler. Also tell me if gfortran uses something other than the Fortran standard while performing automatic typecasting (type conversion).

1

There are 1 answers

1
casey On

Assignment is defined by Fortran 2008 Section 7.2. Of note is Cl. 7.2.1.3 paragraph 8:

For an intrinsic assignment statement where the variable is of numeric type, the expr may have a different numeric type or kind type parameter, in which case the value of expr is converted to the type and kind type parameter of the variable according to the rules of Table 7.9.

Table 7.9: Numeric conversion and the assignment statement

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 it is being assigned to. For character types, derived types and anything else, please see the standard.

Also note that Fortran only performs conversions like this during assignment and initialization but not contexts like procedure calls. For example, consider this procedure:

subroutine sub1(a)
 implicit none
 integer :: a     
 print *, a  
end subroutine

This procedure has a dummy argument of type integer. You cannot, for example, do this:

call sub1(1.d0)

because this results in a mismatch of type between the actual and 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 the implicit conversion is defined for the assignment.


The only documented extension to the standard for implicit type conversion in gfortran (5.1.0) is between logical and integer types during assignment.

See: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gfortran/Implicitly-convert-LOGICAL-and-INTEGER-values.html#Implicitly-convert-LOGICAL-and-INTEGER-values

  • Logical .true. is converted to integer 1
  • Logical .false. is converted to integer 0
  • Integer 0 is converted to .false.
  • Any other integer is converted to .true.

Do note that if you can do without legacy extensions then don't use them. Using them means your program is not standard Fortran and thus any compiler is free to reject it for being incorrect. This extensions is meant to allow legacy code to compile with modern compilers and not for use in new code.