Fortran中受保护的全局变量 [英] Protected global variables in Fortran

查看:290
本文介绍了Fortran中受保护的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Fortran中是否有一种全局变量的方式,可以说是某种受保护的。我正在考虑一个包含变量列表的模块A.使用A的每个其他模块或子例程都可以使用它的变量。如果你知道变量的值是什么,你可以使用参数来实现它不能被覆盖。但是如果你必须先运行代码来确定变量值呢?由于您需要更改它,因此您无法将其指定为参数。有没有一种方法可以在运行时执行类似的操作?

解决方案

您可以使用模块中的PROTECTED 属性。它已在Fortran 2003标准中引入。
模块中的过程可以更改PROTECTED对象,但不包括使用模块的模块或程序。



示例:

  module m_test 
integer,protected :: a
包含
子程序init(val)
整数val
a = val
结束子程序
结束模块m_test

程序测试
使用m_test

调用init(5)
打印*,a
!如果取消注释这些行,编译器应该标记错误
!a = 10
!print *,a
调用init(10)
print *,a
end program


I wonder if there is a way of having a global variable in Fortran, which can be stated as some kind of 'protected'. I am thinking of a module A that contains a list of variables. Every other module or subroutine that uses A can use it's variables. If you know what the value of the variable is, you could use parameter to achieve that it can't be overwritten. But what if you have to run code first to determine the variables value? You could not state it as parameter since you need to change it. Is there a way to do something similar but at a specific point at runtime?

解决方案

You could use the PROTECTEDattribute in a module. It has been introduced with the Fortran 2003 standard. The procedures in the module can change PROTECTED objects, but not procedures in modules or programes that USE your module.

Example:

module m_test
    integer, protected :: a
    contains
        subroutine init(val)
            integer val            
            a = val
        end subroutine
end module m_test

program test
    use m_test

    call init(5)
    print *, a
    ! if you uncomment these lines, the compiler should flag an error
    !a = 10
    !print *, a
    call init(10)
    print *, a
end program  

这篇关于Fortran中受保护的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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