3

How can I write a function in Fortran which takes both input and output as arguments? For example:

fun(integer input,integer output)

I want to make use of the output value. I have tried something like this but the output variable is not holding the value.

Specifically, I am calling a C function from Fortran which takes input and output as parameters. I am able to pass input values successfully, but the output variable is not acquiring a value.

ire_and_curses
  • 68,372
  • 23
  • 116
  • 141

2 Answers2

5

In Fortran, your fun() is called a subroutine. A function is a value-returning thing like this:

sin_of_x = sin(x)

So your first decision is which approach your Fortran code will take. You probably want to use a subroutine. Then sort out the intent of your arguments.

karel
  • 5,489
  • 46
  • 45
  • 50
High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
4

An example. if you want a function that returns void you should use a subroutine instead.

function foo(input, output)
    implicit none
    integer :: foo
    integer, intent(in) :: input
    integer, intent(out) :: output

    output = input + 3
    foo = 0
end function

program test
    implicit none
    integer :: a, b, c, foo

    b = 5
    a = foo(b, c)

    print *,a,b, c

end program 

If you are calling a C routine, then the signature makes use of references.

$ cat test.f90 
program test
    implicit none
    integer :: a, b, c, foo

    b = 5
    a = foo(b, c)

    print *,a,b, c

end program 

$ cat foo.c 
#include <stdio.h>
int foo_(int *input, int *output) {
    printf("I'm a C routine\n"); 
    *output = 3 + *input;

    return 0;
}


$ g95 -c test.f90 
$ gcc -c foo.c 
$ g95 test.o foo.o 
$ ./a.out 
I'm a C routine
 0 5 8

if you use strings, things gets messy.

Stefano Borini
  • 138,652
  • 96
  • 297
  • 431
  • So is the only practical difference between a Fortran function and subroutine that the subroutine doesn't return a value? – naught101 Dec 16 '14 at 05:33
  • @naught101: No, there are other differences, but I have two years of rust accumulated so I don't remember the details anymore. – Stefano Borini Dec 16 '14 at 14:19