j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
178 stars 15 forks source link

Have size(x) return -1 when x is an unallocated ALLOCATABLE array #219

Closed Beliavsky closed 3 years ago

Beliavsky commented 3 years ago

To safely determine the size of an allocatable array one must first check that it is allocated, with code such as

if (allocated(x)) then
   n = size(x)
else
   n = -1
end if

I suggest that the size of an unallocated allocatable array be defined as -1, so that the above code could just be replaced by

n = size(x)

This would simplify code using allocatable arrays.

klausler commented 3 years ago

You could write a small library function with these odd semantics; why should they be in the standard language?

Beliavsky commented 3 years ago

@klausler Separate functions would be needed for each built-in data type and for user-defined types and classes. Maybe for ranks, too, but perhaps functions could be written with assumed rank arguments. I think it's better for the size function to return a value signaling an error than to crash.

klausler commented 3 years ago
module mySizeModule
 contains
  pure integer function mySize(x)
    class(*), dimension(..), intent(in), optional :: x
    mySize = -1
    if (present(x)) mySize = size(x)
  end function
end module

use mySizeModule
integer, allocatable :: a(:), b(:)
allocate(a(10))
print *, mySize(a), mySize(b)
end
Beliavsky commented 3 years ago

Since one person has objected and no one has supported this idea, and since it has been shown how a generic function can be written to produce the requested behavior, I am closing the issue and withdrawing my proposal.

GHNewbiee commented 2 years ago

@klausler Because standard language has to be prudent and provide/promote safe practices by itself.

Please visit the link.

In your opinion: You ask people to close the hole to make the road safe. This is not their job!

FortranFan commented 2 years ago

module mySizeModule contains pure integer function mySize(x) class(*), dimension(..), intent(in), optional :: x

type(*) is another option here: some may prefer that to class(*) because the standard limits the situations where this other unlimited polymorphic entity in type(*) can appear - PRESENT and SIZE intrinsics are allowed; and the compiler is required to detect and report the situations where type(*) argument cannot appear.