Question about `reshape([real ::],n)`

Dear all,

The right-hand side automatically allocating x appears to be an array with dimensions n(1),n(2),n(3), but I don’t really understand what is happening there. Is this valid Fortran? It compiles successfully on ifort, but not the latest gfortran (see answer below) and nvfortran.

implicit none
integer, parameter :: n(3) = [3,2,1]
real, allocatable :: x(:,:,:)
x = reshape([real ::],n)


PS: inspired by this SO answer: fortran - Allocate Multiple Arrays with Single Shape - Stack Overflow

1 Like

This is an ifort compiler bug, in my opinion. If the size of source = [real ::] is less than x, then the pad argument should be present if I remember correctly. The latest gfortran detects the problem correctly. It would be great to report this ifort bug in Intel Fortran Forum. Just put compiler bug or something similar in the title for the developers to notice.


On WSL2, my gfortran is GNU Fortran (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, and it compiles the code you gave. On Windows I have GNU Fortran (GCC) 12.0.1 20220213 installed from , and it says


    4 | x = reshape([real ::],n)
      |            1
Error: Without padding, there are not enough elements in the intrinsic RESHAPE source at (1) to match the shape

Adding the suggested PAD argument, the code

implicit none
integer, parameter :: n(3) = [3,2,1]
real, allocatable :: x(:,:,:)
x = reshape([real ::],n,pad=[-1.0,1.0])

compiles and runs, giving

           3           2           1
  -1.00000000       1.00000000      -1.00000000       1.00000000      -1.00000000       1.00000000

Metcalf, Reid, and Cohen (2018) say

reshape (source, shape [,pad] [,order] ) returns an array with shape
given by the rank-one integer array shape, and type and type parameters those of the
array source. The size of shape must be constant, and its elements must not be negative.
If pad is present, it must be an array of the same type and type parameters as
source. If pad is absent or of size zero, the size of the result must not exceed the size
of source.


Thanks! It seems nvfortran still doesn’t digest this:

$ nvfortran test.f90                                                                                                                                                                                  
NVFORTRAN-S-0074-Illegal number or type of arguments to reshape - keyword argument source (test.f90: 4)
  0 inform,   0 warnings,   1 severes, 0 fatal for MAIN