António Carneiro
António Carneiro

Reputation: 25

Passing arguments by value in Fortran 95

How do you keep the value of a function argument when you call it, without creating a new variable? This is, how can I pass the argument by value?

In this example code:

program what
  implicit none  
  integer :: a, b, c, d

  a = 1
  b = 2
  c = 3

  print *, a,b,c

  d = f(val(a), val(b), val(c))

  print *, d

  print *, a,b,c

  d = f(a, b, c)

  print *, d

contains

  function f(x,y,z) result(h)
    integer:: x,y,z
    integer :: h

    h = x+y+z
    x = 0
    y = 0
    z = 0
  end function
end program

when i call the function the second time, it only prints 0's.

Upvotes: 2

Views: 4025

Answers (1)

In Fortran 95 there is no way. Except some very non-standard extensions, but they are not Fortran 95 nor any other Fortran, just extensions.

In Fortran 2003 use the value attribute.

function f(x,y,z) result(h)

integer, value :: x,y,z

The attribute requires explicit interface, but your example has it, so that is OK.

Upvotes: 5

Related Questions