Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when calling external an Fortran function with the wrong type of arguments?

If you have a standalone function in a file (not in a module) and you call it with a single-precision while it expects a double precision number:

main.f90 :

program main

  call test(1.0)
end program main

test.f90:

subroutine test(a)
    double precision :: a
    print *, "a", a
end subroutine

How does the compiler "casts" from single to double precision in this case ? Using floating-point format, I would expect the bits to stay the same during the cast but additionnal zeroes to be appended. That is:

1 = 0 01111111 00000000000000000000000 in single-precision

and I would expect the final value to be 2^(-7):

0 01111111000 0000000000000000000000000000000000000000000000000000 in double precision

Surprisingly, with gfortran 6.4.0, the final value is 5.2635442471208903E-315.

like image 247
alex_reader Avatar asked Nov 17 '22 07:11

alex_reader


1 Answers

The compiler does no casting. What you have written is not Fortran.

In the main program the subroutine test has an implicit interface. Essentially, the compiler knows nothing about this except that it is a subroutine. You also tell it that it has a single (default) real argument.

It is your responsibility, not the compiler's, to provide the correct type and kind of argument when referencing the subroutine. You failed there, so you do not have a compliant Fortran program. The Fortran compiler owes you nothing.

What you will observe will depend on implementation details of the Fortran processor. The subroutine expects a double precision argument and has no reason to believe it has anything else. Whether there is copy-in/copy-out or some address passing1, the interpretation of memory will not match. In the dummy argument, all but the bytes corresponding to the default real of the actual argument are "junk".

If you provide an explicit interface for the subroutine in the main program there will still be no casting, but the compiler will notice the mismatch. Equally, some compilers (perhaps with certain compile flags) will do some checking even when an implicit interface is there.


1 For details of the likely pass-by-reference, see the comment by user5713492.

like image 70
francescalus Avatar answered Jan 18 '23 04:01

francescalus