2

I have made this small test program to "prove" that you cannot use vectors without specifying their size prior to compilation (or if you make them allocatable). My point failed though. I was expecting that the local vector "num" would fail. The program cannot know the size of it before execution of the program. The size, nod, is read from the user at execution. I compile with the following command:

gfortan -fcheck=all test.f90

The value of "nod" was given as 500000000 during execution

The version of gfortran is 6.3.0

The execution went "fine" and returned the following answer:

7 9.9000000000000004 9.9000000000000004 500000000

So my question is; why doesn't the compiler throw errors to me that I'm writing outside a (non-defined) vector? I guess it sees my mistake and saves me?? By making it allocatable?? or am I totally wrong here?

MODULE globaldata
  IMPLICIT NONE
  INTEGER nod
END MODULE globaldata

MODULE modtest
  USE globaldata
  IMPLICIT NONE

CONTAINS
  SUBROUTINE mysubtest(dummy)
    IMPLICIT NONE
    INTEGER :: dummy
    REAL(kind=8) :: num(nod)

    dummy = 7
    num = 9.9d0
    write(*,*) dummy,num(1),num(nod),size(num)

  END SUBROUTINE mysubtest

END MODULE modtest

PROGRAM test
  USE globaldata
  USE modtest
  IMPLICIT NONE
  INTEGER dummy1

  WRITE(*,*)"Give the value of nod:"
  READ(*,*) nod
  CALL mysubtest(dummy1)

END PROGRAM test
francescalus
  • 30,576
  • 16
  • 61
  • 96
Andreas
  • 27
  • 4

1 Answers1

2

One certainly can have explicit-shape arrays which have sizes not known at compile-time (using a named or literal constant/constant expression). These entities are called automatic objects. They are, however, restricted in where they may appear.

An explicit-shape array may appear in a specification part of any program unit. Variables in the scope of main programs or modules must indeed have sizes that are constant expressions. More generally, array size expressions for explicit-size arrays are specification expressions and for local variables these expressions do not need to be constant expressions.

In your test case the array num is a local variable of mysubtest. nod is a module variable, accessible through host association (and use association in that host) , and so forms a quite valid specification expression: the array num has size nod in mysubtest, whatever the value of nod when the subroutine is invoked.

Details of what are allowed in a specification expression can be found Fortran 2018, 10.1.11.

Automatic objects may appear in other places or be automatic for reasons other than array size, but this is not relevant to the case of the question.

francescalus
  • 30,576
  • 16
  • 61
  • 96
  • Thank you for the answer @francescalus ! I'm just on a very basic level, but I will read up on your answer and particularly on the link in your comment to the question. – Andreas Nov 29 '19 at 11:07