Fortran functions and return values

11,536

Solution 1

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.

Solution 2

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.

Share:
11,536
Admin
Author by

Admin

Updated on June 08, 2022

Comments

  • Admin
    Admin over 1 year

    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.