0

Could someone explain why the following Fortran code compiles and runs?:

PROGRAM wrong_array_shape

  IMPLICIT NONE
  REAL :: x(2)
  INTEGER :: n

  x = 1.
  n = 2

  WRITE(*, *) f(x, n)

CONTAINS

  REAL FUNCTION f(x, n)

    IMPLICIT NONE
    INTEGER, INTENT(IN) :: n
    REAL, INTENT(IN) :: x(n, n)

    f = x(1, 1)

  END FUNCTION f

END PROGRAM wrong_array_shape

The array x that is declared in the main program is a one-dimensional array of length 2, while the function is expecting a two-dimensional array of size n x n. I expected this to fail to compile and/or fail to run, but it runs fine and writes out the result 1.000000... to the screen.

I would like to have a compile-time warning (or preferably a fail) when compiling code that contains errors like this.

In case is is relevant, I am using gfortran 9.2.0 and compile with no special flags, I compile simply with gfortran wrong_array_shape.f90.

Mead
  • 383
  • 4
  • 19
  • You do have an error in this program (the array `x` is expected to have four elements in the subroutine but is only 2 elements in size), but it isn't a syntax error to pass a 1-D array to an explicit shape 2-D array in a subroutine. It may be a programming error, but it's not a violation of the Fortran language so you're on you own detecting this logical error. – francescalus May 27 '20 at 11:40
  • If you want this diagnosed look into using an assumed shape array for the dummy argument - the compiler will then flag it – Ian Bush May 27 '20 at 11:47

0 Answers0