Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected global variables in Fortran

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?

like image 576
DaPhil Avatar asked Feb 22 '13 09:02

DaPhil


People also ask

Does Fortran have global variables?

Fortran 77 has no global variables, i.e. variables that are shared among several program units (subroutines). The only way to pass information between subroutines we have seen so far is to use the subroutine parameter list.

Does Fortran have local variables?

Modern Fortran compilers typically use memory differently and local variables of procedures do not always retain their values if SAVE is omitted. This frequently causes bugs when old programs are compiled with current compilers. Compilers typically provide an option to restore the old behavior.


1 Answers

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  
like image 69
Johny Bergmann Avatar answered Sep 19 '22 23:09

Johny Bergmann