22.03.2013 Views

Self study guide: Fortran 95 - University of Cambridge

Self study guide: Fortran 95 - University of Cambridge

Self study guide: Fortran 95 - University of Cambridge

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

program set<br />

implicit none<br />

real :: a, b<br />

! Read in value <strong>of</strong> a<br />

read(*,*) a<br />

call setval(b)<br />

write(*,*) b<br />

contains<br />

subroutine setval(x)<br />

real :: x<br />

x = a ! value <strong>of</strong> a is from main program<br />

end subroutine setval<br />

end program set<br />

This program is very contrived, it simply sets the value <strong>of</strong> the argument <strong>of</strong> the call to<br />

setval to the value <strong>of</strong> the variable a in the main program. In this example a is a<br />

variable global to the main program and the subroutine setval.<br />

5.5 Passing arrays to subroutines and functions<br />

Arrays can <strong>of</strong> course be used as arguments to subroutines and functions,<br />

however there are one or two special considerations.<br />

5.5.1 Size and shape <strong>of</strong> array known<br />

If the size and shape <strong>of</strong> the array are known, one can simply repeat the definition in<br />

the subroutine when the arguments are declared. For example, if v and r are vectors<br />

<strong>of</strong> length 3 a subroutine declaration in which they are passed would look like:<br />

subroutine arr1(v, r)<br />

real :: v(3)<br />

real :: r(3)<br />

and <strong>of</strong> course you could have used the alternative form using dimension instead:<br />

subroutine arr1(v, r)<br />

real, dimension(3) :: v, r<br />

5.5.2 Arrays <strong>of</strong> unknown shape and size<br />

The problem is how to deal with arrays <strong>of</strong> unknown length. This is important when<br />

for example we wish to write a subroutine which will work with arrays <strong>of</strong> many<br />

different lengths. For example, we may wish to calculate various statistics <strong>of</strong> an<br />

array. We can in this case use the following definition:<br />

35

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!