DIMENSION V1(3),V2(3) . . . 100 PROD=DOT(V1,V2) . . . END FUNCTION DOT(A,B) C Calculate the scalar product of A and B DIMENSION A(3),B(3) DOT=0. DO 10 I=1,3 10 DOT=DOT+A(I)*B(I) RETURN END
Statement 100 in MAIN might, at first glance, appear to be the assignment of an array element of an array DOT to a variable PROD. However there is no DIMENSION statement for DOT so FORTRAN knows it cannot be an array and generates a call to the function DOT instead. Function DOT finds the scalar product of the two vectors passed to it and stores the result in a local variable with the same name as the function. When it returns the value in the local variable DOT is passed back to the calling routine and statement 100 continues with the construction DOT(V1,V2) replaced by the function value. In general, a function can have any number of arguments of any type but, unlike a subroutine, must have at least one (for otherwise FORTRAN would not be able to recognise the function call). A function can modify its arguments but it is not good practice to do so - the idea of a function is that it returns a single value which is dependent on its input arguments. FUNCTIONS can return any type of data. For reals and integers the function name can rely on the implicit I,J,K,L,M,N rule, but other types i.e. logical and character must explicitly declare their type both in the calling routine and in the FUNCTION statement. For example:-
LOGICAL TEST A=1.0 B=5.0 IF (TEST(A,B)) PRINT *,'B is greater than A' STOP END LOGICAL FUNCTION TEST(X,Y) C See if second argument is greater than the first TEST=Y.GT.X RETURN END
This example also shows a function call being used as the value of a logical expression within a logical IF. Indeed a function call may be used wherever an expression of the same type is valid. This includes arguments to other function calls so all the following statements are legal:-
SUM=DOT(V1,V2)+DOT(V2,V3)/DOT(V3,V1) IF (X.GT.DOT(V1,V2)) GOTO 100 IF (TEST(DOT(VI,V2),DOT(V2,V3)) GOTO 200
Write a function CALC(A,OP,B) that takes two real arguments A and B and a 1 character string OP that should have one of the 4 values '+','-','*',or '/', indicating the way A and B are to be combined to produce the value to be returned. E.g. CALC (2.0,'+',3.5) would return 5.5. Write a MAIN routine to test it and show that even the construction :-
CALC(CALC(A,OP,B),OP2,CALC(A2,OP3,B2))is legal!