Allocatable array is a dynamic array. It’s size is not know at compilation time. Therefore it is defined at execution time by using the keyword allocate(…).

It’s life scope is kept where it is defined. Once the procedure/… reaches the end it is automatically deallocated (or released).

Nevertheless, you should be careful when using allocatable arrays and all builtin method. The compiler does not detect the different sizes. So it provides a false positive when tested with the first value  of the array.

Check below an example:

program allbug
  implicit none
  real, allocatable :: values(:,:)
  allocate(values(3,1))
  values(:, 1) = [26., 27., 28.]
  write(*,*) "values= ", values
  write(*,*) "the same vs 26?", all(values(:, 1) == [26.] )     
  write(*,*) "the same vs 27?", all(values(:, 1) == [27.] )
end program 

 The output:

 bash:~/projects$ ./a.out
   values=  26.0000000    27.0000000    28.0000000
   the same vs 26? T  <---- HERE!
   the same vs 27? F 

On the other hand, when it is done with an explicit array an error is raised at compilation time.

  all-fixed.f90:10:36-51:
      10 |  write(*,*) "the same vs 26?", all(values(:, 1) == [26.] )
       |                  1       2
    Error: Shapes for operands at (1) and (2) are not conformable
    all-fixed.f90:11:36-51:      11 |  write(*,*) "the same vs 26?", all(values(:, 1) == [27.] )
       |                  1       2
    Error: Shapes for operands at (1) and (2) are not conformable   

Tests under gfortran 9.3

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *