Why do I need to declare the type of a function everywhere I use it?

StackOverflow https://stackoverflow.com/questions/23418974

  •  13-07-2023
  •  | 
  •  

سؤال

Consider the following FORTRAN program:

program functiontest
    implicit none
    real :: x, square
    print *, "Enter a number to square"
    read (*,*) x
    print *, square(x)
end program functiontest


real function square(x)
    real :: x
    square = x * x
end function square

Why do I need to declare square to be real inside program functiontest? Haven't I already declared it a real function in its definition?

Why did the authors of FORTRAN make this design decision?

هل كانت مفيدة؟

المحلول

No, actually in your example you haven't declared it a real function inside the program, but it's an external function to the program. If you defined your function inside the program, as follows, or put it in a module and used it, you wouldn't have to specify it's a real function twice.

program functiontest
    implicit none
    real :: x
    print *, "Enter a number to square"
    read (*,*) x
    print *, square(x)

contains
    real function square(x)
        real :: x
        square = x * x
    end function square
end program functiontest

As for why it also works the way you wrote it, it is for backwards compatibility with Fortran 77.

نصائح أخرى

Put the function in a module and use the module, as shown below. Then you don't need to declare the function in the main program.

module foo
contains
real function square(x)
    real :: x
    square = x * x
end function square
end module foo

program functiontest
    use foo
    implicit none
    real :: x
    print *, "Enter a number to square"
    read (*,*) x
    print *, square(x)
end program functiontest

The square inside the function is a variable, and is not the function name. Since it is a variable, it must be declared with the right type.

I think you need to declare the type in functionlist because "in general" compiler doesn't know the type of "square". Consider a case that you have function "square" defined in a separate file, i.e. "square.f", and functionlist in another file "functionlist.f". In that case you need to compile each of those files separately and create two object file, i.e. square.o and functionlist.o. In this scenario, compiler has no clue about the "square" type, when compiling for "functionlist.o", unless you explicitly define it.

So you might ask why compiler needs to know the type of square in the first place. The answer, I think, is related to memory allocation, casting the type (e.g. when you are assigning the results to a real*8), ....

Note that, this is also common in C. There, you either need to define the prototype (in foo.h), in which the type of square is declared, or place all the functions in a file such that compiler "sees" square first.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top