3

I'm sure the solution to this is extremely basic, but I'm having a hard time figuring out how to use functions in Fortran. I have the following simple program:

  PROGRAM main
    IMPLICIT NONE
    INTEGER :: a,b
    a = 3
    b = 5
    PRINT *,funct(a,b)
  END PROGRAM

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION

I've tried several variations of this, including assigning a data type before FUNCTION, assigning the result of funct to another variable in the main program and printing that variable, and moving the FUNCTION block above the PROGRAM block. None of these worked. With the current program I get an error on line 6 (the line with the PRINT statement):

Error: Return type mismatch of function 'funct' (UNKNOWN/INTEGER(4))
Error: Function 'funct' has no IMPLICIT type

From all of the guides I've tried, I seem to be doing it right; at least one of the variations, or a combination of some of them, should have worked. How do I need to change this code to use the function?

2
  • the problem is that you used implicit none while you did not give funct a declaration. you must add integer ,external :: funct. Commented Aug 29, 2017 at 8:20
  • Thanks, both this and Pierre's answer worked. Commented Aug 30, 2017 at 0:01

2 Answers 2

5

Simply putting the function in the file will not make it accessible to the main program.

Traditionally, you could simply declare a function as external and the compiler would simply expect to find a suitable declaration at compile-time.

Modern Fortran organizes code and data in "modules". For your purpose, however, it is simpler to "contain" the function within the scope of the main program as follows:

PROGRAM main
  IMPLICIT NONE
  INTEGER :: a,b
  a = 3
  b = 5
  PRINT *,funct(a,b)

CONTAINS

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION funct
END PROGRAM main
Sign up to request clarification or add additional context in comments.

Comments

0

A simpler solution can be the following code

 PROGRAM main
    IMPLICIT NONE
    INTEGER :: a,b, funct
    a = 3
    b = 5
    PRINT *,funct(a,b)
  END PROGRAM

  FUNCTION funct(a,b)
    IMPLICIT NONE
    INTEGER :: funct
    INTEGER :: a,b

    funct = a + b
  END FUNCTION

where the only difference is in the third line, where I have declared funct as an integer. It compiles and it prints 8 as result.

2 Comments

You've (correctly) declared funct's return type as integer not real. For general circumstances, though, this is quite bad advice.
Thanks a lot, I am quite new to Fortran.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.