2

In the program below, there are two methods presented for passing an array:

program main
    integer, dimension(4) :: x = [9, 8, 7, 6]
    call print_x(x(2:3))   ! Method 1
    call print_x(x(2))     ! Method 2
end program

subroutine print_x(x)
    integer, dimension(2), intent(in) :: x
    print *, x
end subroutine

Both methods produce the same result: the numbers 8 and 7 are printed. Personally, I would never code this using Method 2 because it looks like a single value is being passed rather than an array.

Can you give an example of when Method 2 MUST be used instead of Method 1?

6
  • I would use neither. Stick all your subprograms in a module or as contained subprograms and use assumed shape for your dummy arguments. Both the above methods are holdovers from archaic standards. Commented Jul 16, 2019 at 19:34
  • @IanBush, when you want to have elements 2 and 3 of the array associated with the dummy then certainly case 1 seems quite natural to me. What have you against that? Commented Jul 16, 2019 at 19:35
  • @francescalus Lack of an interface in scope is what I have against it Commented Jul 16, 2019 at 19:42
  • @IanBush, ok. Assuming an explicit interface in scope would your statement still hold? Commented Jul 16, 2019 at 19:46
  • @francescalus If there's an interface in scope I would still much prefer assumed shape for the dummy argument - we've recently seen compilers unable to diagnose a mismatch between the declared shape of the dummy argument and the actual argument. But if you applied the thumb screws I would eventually, reluctantly, come down in favour of method 1. Commented Jul 16, 2019 at 19:50

1 Answer 1

2

Consider the program

  implicit none
  integer :: x(2,2)=0
  call set(x(2,1))
  print*, x

contains

  subroutine set(y)
    integer y(2)
    y = [1,2]
  end subroutine set

end program

The dummy argument y in this subroutine call is argument associated with the elements x(2,1) and x(1,2). There is no array section of x which consists of exactly these two elements.

Sign up to request clarification or add additional context in comments.

3 Comments

I see! This does indeed seem to be an application where Method 1 doesn't work but Method 2 does. This answers the question. That being said, I think we would probably agree that this isn't an ideal methodology, as I mentioned in the original post and as mentioned by @IanBush. Thanks!
Indeed. This is a very specific scenario and the casual reader shouldn't jump to conclusions about its wider utility or desirability.
Right. I am a little surprised that this feature exists in Fortran, but perhaps that is a discussion for another day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.