Function has no implicit type

2019-01-27 16:39发布

问题:

I am trying to learn to work with functions. I have the following code:

program main
  implicit none

  write(*,*) test(4)
end program

integer function test(n)
  implicit none
  integer, intent(in) :: n
  integer :: i, ans

  ans=1
  do i=1,n
  ans=ans*i
  enddo

  test=ans
end function test

When I compile (with gfortran 4.1.2), I get the following error:

In file test.f90:4

  write(*,*) test(4)
           1
Error: Function 'test' at (1) has no IMPLICIT type

回答1:

Move the line

end program

to the end of your source file and, in its place, write the line

contains

As you have written your program it has no knowledge of the function test, which is what the compiler is telling you. I have suggested one of the ways in which you can provide the program with the knowledge it needs, but there are others. Since you are a learner I'll leave you to figure out what's going on in detail.



回答2:

Just in case, someone has the same problem an alternative way (especially for the case discussed in the comment) is to add

integer,external :: test

after

implicit none

in the main program.



回答3:

Just put this:

program main
  implicit none

integer test

  write(*,*) test(4)
end program
...

You need to declare the function as a variable for the compiler to know the return type of the function.