Fortran procedure pointer points to a subroutine that does nothing

你说的曾经没有我的故事 提交于 2019-12-25 07:38:32

问题


I have a code like this

:
procedure(),pointer :: p
if ()
  p => job1
else
  p => job2
endif

do i=1,a_big_number
  call x(...)
  call p(i,j,k)
enddo

The subroutine 'job1' does some work, but the subroutine 'job2' does nothing. In other words, under some circumstances, I need to finish 'x' and 'job1'. Under other circumstances, I only need to do 'x'. My question is how should I define job2. It seems simply using null() does not work. What I am doing right now is like:

subroutine job2(i,j,k)
integer,intent(in) :: i,j,k
end subroutine

However, this looks silly, and I got a lot compiling warning when I compiled the code because those arguments were not used. Is there a smarter way to do this?


回答1:


You could nullify the procedure pointer in the case that there was nothing useful to do, and then test the association status prior to invoking the procedure through the pointer.

PROCEDURE(interface_that_matches_job1), POINTER :: p
IF (...) THEN
  p => job1
ELSE
  NULLIFY(p)   ! Or p => NULL()
END IF

DO i = 1, a_big_number
  CALL x(...)
  IF (ASSOCIATED(p)) CALL p(i,j,k)
END DO



回答2:


If your concern is really about the if statement in the loop, you could just put the if statement outside of the loop:

if (condition) then
  do ii = 1, big_number
    call x(...)
    call p(i,j,k)
  end do
else
  do ii = 1, big_number
    call x(...)
  end do
end if

Then do some timings on this version and then on a version with the if inside the loop:

do ii = 1, big_number
  call x(...)
  if (condition) then
    call p(i,j,k)
  end if
end do

I'd rather guess that you won't see any significant difference between them, as the subroutine call in the loop may already giving you an overhead much larger as the one caused by the if statement.



来源:https://stackoverflow.com/questions/15304959/fortran-procedure-pointer-points-to-a-subroutine-that-does-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!