如果不存在可选参数,我们可以避免创建局部变量吗? [英] Can we avoid creating a local variable if an optional argument is not PRESENT?

查看:22
本文介绍了如果不存在可选参数,我们可以避免创建局部变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Fortran 95 的 PRESENT 语句时遇到问题.目前我正在使用 Silverfrost 的 Plato 及其 FTN95 编译器(在Release Win32"模式下).我想做的是创建一个子程序 SUB(a,b),其中 b 是一个可选变量.到目前为止一切顺利,但是当我尝试使用 if (.NOT.present(b)) b=0b 赋予新值时出现问题.这是代码:

I am having a problem with the PRESENT statement with Fortran 95. Currently I am using Silverfrost's Plato and their FTN95 compiler (in "Release Win32" mode). What I wanted to do is to create a subroutine SUB(a,b), where b is an optional variable. So far so good, but the problem arises when I try to give a new value to b with if (.NOT. present(b)) b=0. This is the code:

module MOD
contains
  subroutine SUB(a,b)
  implicit none
  integer :: a
  integer,optional :: b
  if (.NOT. present(b)) b=0
  print*, a,b
  end subroutine SUB
end module MOD

program TEST
use MOD
implicit none

integer :: i=2, j=1

call SUB(i,j)
call SUB(i)
call SUB(j)

end program TEST

是否有一种优雅的方法来解决这种情况,或者我真的需要创建另一个变量,例如 b_aux,然后使用以下代码?:

Is there an elegant way out of this situation, or do I really need to create another variable, b_aux for instance, and then use the following code?:

if (present(b)) then
  b_aux=b
  else
    b_aux=0
endif

推荐答案

不能使用不存在的变量,所以需要辅助局部变量等方法.

You can't use a non-existent variable, so an approach such as the auxiliary local variable is needed.

这篇关于如果不存在可选参数,我们可以避免创建局部变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆