Silverfrost Forums

Welcome to our forums

Query related to module variables

17 May 2015 10:59 #16311

When we write a standalone subroutine, with arguments say A, B, C, we can prevent the subroutine changing A and B by using the INTENT(IN) statement.

Now if the subroutine is contained in a module, A and B could be declared as module variables, then they become available to the subroutine (i.e. they are not required to be passed to the subroutine as arguments). If my understanding is correct, this produces faster running code as no copying of variables is required?

Question – is there a way of preventing the subroutine code (i.e. a programming error) inadvertently changing A or B, when declared as module variables?

Thanks

Ken

17 May 2015 12:30 (Edited: 17 May 2015 10:27) #16312

A limited amount of protection from inadvertently changing a module variable is obtainable using the PROTECTED attribute. This attribute is available in Fortran 2003 and later, but some F95 compilers implement PROTECTED.

Unwanted changes to module variables can be caused when you 'forget' to provide declarations for local variables in a subprogram that USEs a module, and the module has declarations for variables with the same names. You can control this by using the PUBLIC and PRIVATE attributes with selected variables, and by using the ONLY clause in USE statements, all these being features supported in Fortran 95.

17 May 2015 8:17 #16313

As we don't have PROTECTED in this compiler, you can prevent writing to module variables by declaring your function or subroutine as pure (reading will be allowed).

18 May 2015 7:11 #16314

Thanks David, PURE does what I need - I've never seen it used before.

Please login to reply.