Continuing with the lessons on fortran, the following stuff were covered today.
Procedures in detail
Intents:
A fortran function’s parameters may have three possible intents
in
out
inout
|
|
Note that the result variable doesn’t (and cannot) have intent.
Call by reference:
By default, fortran calls by reference. Hence, if a variable is modified in function, it is reflected in the calling program.
Call by value:
In order to call a parameter by value (that is not to modify orginal variable), the following syntax is followed during declaration inside the procedure.
|
|
Keyword Arguments:
Fortran supports calling procedures with keywords. When done so, the order doesn’t matter (need not be the same order as the function/subroutine declaration).
|
|
Optional Arguments:
Add optional arguments to functions and subroutines.
|
|
Persistent values:
These values are stored and can be retrieved during next function calls.
|
|
Pure Procedures:
Compiler generates efficient code when a procedure is declared as pure.
|
|
To be a pure procedure, the following should be followed.
- All arguments must have intent
in
orinout
(in case of subroutine). - no persistent (
save
) variables - I\O (read, print, write) not allowed.
- stop statement not allowed.
- cannot be recursive.
- if any other procedure is called, that must also be pure.
Recursion:
In Fortran, recursive functions are usually less efficient than iterative counterparts.
|
|
Scope:
Scope is usually limited to the main program or module. So, a variable declared in a program will be accessible to the procedures it contains. However, if the same variable name is declared in a function, that variable will have a local scope within that function.
Modules can be imported (after compiling it first) into another program. It also imports all the corresponding values. Hence, only
is preferred to limit what we import.
|
|
Block statements have the scope limited to within that section.
|
|
Control Flow Statements
Select statement:
It’s similar to switch case of C and is limited to only integer or character values
|
|
where statement
It’s similar to logical indexing in python
|
|
In fortran,
|
|
merge statement
If there are only two cases, merge can be used.
|
|
Exit and cycle statements
exit
exits the loop it is incycle
skips the following codes and go to the next iteration.stop
stops the entire program
If the loop is labelled, then exit and cycle can specify which loop it has to consider.
|
|
Forall and do concurrent statements
These statements allow the compiler to optimize the iterations that has to be performed. Hence, the values in each iteration must be independent of previous iteration.
forall
is restrictive in the sense that it can only be used for assignment of an array.
|
|
do concurrent
is more general in that regard.
|
|
Here is one cool way to develop a band matrix with a width of 3.
|
|
That’s it, for now!