Fortran 2003/2008:优雅的默认参数? [英] Fortran 2003 / 2008: Elegant default arguments?

查看:196
本文介绍了Fortran 2003/2008:优雅的默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在fortran中,我们可以定义默认参数.但是,如果不存在可选参数,则也无法设置该参数.当使用参数作为具有默认值的关键字参数时,这会导致诸如

In fortran, we can define default arguments. However, if an optional argument is not present, it can also not be set. When using arguments as keyword arguments with default values, this leads to awkward constructs like

PROGRAM PDEFAULT 

  CALL SUB
  CALL SUB(3)

CONTAINS 
  SUBROUTINE SUB(VAL)
    INTEGER, OPTIONAL :: VAL
    INTEGER :: AVAL ! short for "actual val"

    IF(PRESENT(VAL)) THEN
       AVAL = VAL
    ELSE 
       AVAL = -1   ! default value 
    END IF

    WRITE(*,'("AVAL is ", I0)') AVAL
  END SUBROUTINE SUB

END PROGRAM PDEFAULT

我个人经常遇到偶然输入VAL而不是AVAL的问题,即接口中的变量名与代码中使用的初始化值之间的断开连接可能会引入运行时错误-更不用说了这种初始化方式非常冗长.

Personally, I often ran into the problem of accidentially typing VAL instead of AVAL, i.e. the disconnect between the variable name in the interface, and the initialized value used in the code can introduce runtime bugs – let alone that this manner of initialization is rather verbose.

是否有一些更优雅的方法来使用带有默认值的可选参数?

Is there some more elegant way of using optional arguments with a default value?

示例写类似

IF(NOT(PRESENT(VAL))) VAL = -1 

因为它避免了VALAVAL的混淆.但这是无效的,大概是因为Fortran通过引用传递了参数,因此,如果CALL语句中不存在VAL,则没有内存与VAL关联,并且VAL = -1会导致段错误.

because it avoids the VAL vs AVAL confusion. But it isn't valid, presumably because Fortran passes arguments by reference and thus if VAL is not present in the CALL statement, no memory is associated with VAL and VAL = -1 would cause a segfault.

推荐答案

您很好地描述了这种情况.我没有别的办法知道这是符合标准的.人们经常使用带有类似名称的局部变量的模式.另一种选择是将if (present()) else放在任何地方,但这很尴尬.

You described the situation rather well. There is no other way I am aware off and that is standard conforming. The pattern with a local variable named similarly is what people often use. The other option is to just put if (present()) else everywhere, but that is awkward.

关键是它们是可选参数,而不是 default 参数. Fortran没有默认参数.可能更好,但这不是委员会成员在准备Fortran 90时在80年代选择的.

The point is that they are optional arguments, not default arguments. Fortran doesn't have default arguments. The may have been better, but that is not what the committee members have chosen in the 80s when preparing Fortran 90.

这篇关于Fortran 2003/2008:优雅的默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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