Fortran references to variables - fortran

I am extremely new to Fortran, so forgive any ignorance in this question.
Anyway I am working on optimizing some simulation software.
To be more clear the subroutine I am editing initializes some static variables at the start and they should be the same no matter what the starting conditions are.
The problem is I have another piece of coding calling this subroutine across each of its time steps reinitializing hundreds of variables, that should have just stayed the same. To fix this I have created a derived type that includes all these variables from other modules in the program, and I am editing the software to initialize the derived type variables instead of the module variables so that I can just refer across different time steps.
My question is, am i doing uneeded work. If I instead just took all the initialization stuff and put it in a subroutine outside of my main program, and then linked these at compilation, would all the variables retain their values across function calls.

If you have a variable that should be initialized once and never changed, give it the parameter attribute:
real, parameter :: pi = 3.141592
The compiler will treat the "variable" as a constant that can't be changed. If you mistakenly try to change such a variable, the compiler will inform you of your mistake.
Does this answer your question?

I can't tell what you are doing, but FORTRAN is a 3GL and it passes parameters by reference. If you want variables from the main to be in subroutines, you need to put it in a common block. COMMON blocks are like global variables in C.

Related

Is there any way to write EQUIVALENCE for a variable in a fortran Module?

Umm I've came across a problem in Fortran where I need to use Equivalence for a variable which is already declared in a module written by someone else(Probably is dead by now, otherwise I would have contacted him/her).
The variable in the module is of REAL type. And I want to store a INTEGER value in it.
If I do so directly, wrong data gets stored in the REAL type.
I have tried to use equivalence in module, But no luck.
Any Help ?
Well, EQUIVALENCE is an old keyword which should be avoided in modern Fortran because it makes the code misleading, but it has not been eliminated from Fortran standard yet, AFAIK.
However, if you have just the need to store the bit-by-bit representation of a integer in a real variable, I'd rather suggest to use the intrinsic function TRANSFER which literally transfers the binary contents of a variable to a variable of another type without any conversion and without raising errors. So, assuming that your real module variable is x and your integer value is i you can simply do:
x = TRANSFER(i,x)
The second argument could be any real variable, not necessarily x itself, it just gives a hint to the compiler that the result is of real type and it should not be an error to assign it to a real variable.

Difference between newer implementation and older implementations

I am a newbie to Fortran. Please look at the code below:
c main program
call foo(2)
print*, 2
stop
end
subroutine foo(x)
x = x + 1
return
end
In some implementations of Fortran IV, the above code would print a 3. Why is that? Can you suggest an explanation?
How do you suppose more recent Fortran implementations get around the problem?
Help is very much appreciated. Thank You.
The program breaks the language rules - the dummy argument x in the subroutine is modified via the line x = x + 1, but it is associated with something that is an expression (a simple constant). In general, values that result from expressions cannot be modified.
That specific code is still syntactically valid Fortran 2008. It remains a programming error in Fortran 2008 - as it was in Fortran IV/66. This isn't something that compilers are required to diagnose. Some may, perhaps with additional debugging options, and perhaps not till runtime.
Because the program breaks the language rules anything could happen when you run the program. Exactly what depends on the code generated by the compiler. Compilers may have set aside modifiable storage for the value that results from the expression such that it internally looks like a variable (the program might print three and the program carries on), that modifiable storage might be shared across the program for other instances of the constant 2 (suddenly the value of 2 becomes three everywhere!), the storage for the value of the constant might in non-modifiable memory (the program may crash), the compiler may issue an error message, the program may get upset and sulk in its bedroom, the program might declare war on a neighbouring nation - it is a programming error - what happens is unspecified.
As of Fortran 90, facilities were introduced into the language to allow programmers to write new code that is practical for compilers to check for errors such as these (and in some cases compilers are required to check for errors if they are to be regarded as standard conforming).
For the code as presented, the main program and the subroutine are to be regarded as separately compiled - the main program is unaware of the details of the subroutine and vice versa (it is possible that the subroutine could be compiled long after the main program, on a different machine, with the outputs of the two being linked together at some later stage - without fancy link time behaviour or static analysis it is therefore not possible to resolve errors such as this). Language rules are such that when compiling the main program the compiler must implicitly assume the details of the interface of the subroutine based only on the way the subroutine is referenced - inside the main program the subroutine has an implicit interface.
Fortran 90 introduced the concept of an explicit interface, where the compiler is explicitly told what the interface of the subroutine in various ways, and can then check that any reference to the subroutine is consistent with that interface. If a procedure is a module procedure, internal procedure or intrinsic procedure - that interface is automatically realized, alternatively for external subprograms, procedure pointers, etc, the programmer can explicitly describe the interface using an interface block.
In addition, Fortran 90 introduced the intent attribute - a characteristic of a dummy argument of a procedure that is also then a characteristic of the interface for a procedure. The intent of the argument indicates to the compiler whether the procedure may define the argument (it also may implications for default initialization and component allocation status) and hence whether an expression could be a valid actual argument. x in subroutine foo would typically be declared INTENT(INOUT).
Collectively these new language features provide a robust defence against this sort of programming error when using compilers with a basic level of implementation quality. If you are starting with the language then it is recommended that these new features become part of your standard approach - i.e. use implicit none, all procedures should generally be module procedures or internal procedures, use external procedures only when absolutely required, always specify dummy argument intent, use free form source.

C++ : how to make sure all variables are initialized?

Recently I had lots of trouble with a non initialized variable.
In Java, the default value of variable is null, therefore an exception is likely to be thrown when if the non-initialized variable is used. If I understood, in C++, the variable is initialized with whatever data turns out to be in the memory. Which means that the program is likely to run, and it might be hard to even know there is something wrong with it.
What would be the clean way to deal with this ? Is there some good programming habit that would reduce the risk ? In my case, the variable was declared in the header file and should have been initialized in the cpp file, which is an example of things that makes error more likely.
thx
Edition after receiving few answers:
My apologies, my question was not specific enough.
The answer I get to use flag for the compilers to get informed of non-initialized variables will be useful.
But there are rare cased variables can not be initialized at the beginning, because depending on the behavior of your system.
in header file
double learnedValue;
in cpp file
/* code that has nothing to do with learnedValue
...
*/
learnedValue = a*b*c; // values of a, b and c computed in the code above
/*code making use of learned value
...
*/
Now what happened is that forgot the line "learnedValue=a*b*c".
But the program was working good, just with value of learnedValue initialized with whatever what was in the memory when it was declared.
In Java, such error is not an issue, because the code making use of learned value is likely to crash or throw an exception (at least you get to know what was wrong).
In C++, you can apparently be happy and never get to know there is a problem at all. Or ?
Pls make sure you have appropriate warning levels set while compiling your program.
Compilers issue appropriate warning whenever un-initialized variables are used.
On g++, -Wall compiler option would show all warnings.
On Visual studio, you might have to use warning level 4.
Also, there are some static code analysis tool available in the market.
cppCheck is one such tool available for free.
You should not define a variable in a header (only declare it). Otherwise you will get other errors when you include the header in several .cpp files.
When actually defining a variable, you can also give it an initial value (like 0). In C++ it is also common to defer the definition of (local) variables until you have a value to assign to them.
In the header file
extern double learnedValue;
^^^^^^
In the cpp file
double learnedValue = 0;
/* code that has nothing to do with learnedValue
...
*/
learnedValue = a*b*c; // values of a, b and c computed in the code above
/*code making use of learned value
...
*/
you can define the variables on the spot they are declared
c++11 allows you to initialize variables inside class. If that is not implemented by the compiler yet then the constructor initialization list is the area to check.
The C# can initialize the variable. But C++ not, so when use a pointer without initialized, it always throw exception. You should make a good habit to initialize all the variables in the class constructor.

Where does FORTRAN store local variables?

from the source code published in the programmer's manual of a commercial program, I have isolated a code snippet which puzzles me quite a lot.
The function below is expected to be called multiple times by a kernel and is supposed to implement the temporal behaviour of a component in a system consisting of many interconnected components (I have removed the Input/Output parameters from the function prototype because they are irrelevant to the point I intend to rise).
To distinguish between different instances of the same block type the kernel pass an instance number in the INFO(1) element.
As far as I have understood, the designer of this program took a great deal of effort trying to save the time spent in copying the values of the parameters from the PAR vector to local variables with meaningful names at each call (as if they were not aware of the optimizations a compiler can do). It seems to me that they wanted to assign them to the local variables only in the first call, or when the caller switch to a different instance of the same type.
However I can't understand how this could work if the local variables are not declared static with the "save" keyword. Does FORTRAN store local variables statically i.e. not on a stack? (I am sorry if the question sounds stupid, I am used to the C/C++ languages)
Thank you.
SUBROUTINE TYPE151(PAR, INFO, *)
IMPLICIT NONE
INTEGER*4 INFO(15), IUNIT
DOUBLE PRECISION PAR, QMAX
PARAMETER (NP=1)
DIMENSION PAR(NP)
! First call
IF (INFO(7).EQ.-1) THEN
IUNIT = INFO(1)
QMAX = PAR(1)
RETURN 1
ENDIF
! later calls
IF(INFO(1).NE.IUNIT) THEN
IUNIT = INFO(1)
QMAX = PAR(1)
ENDIF
! Making use of QMAX in some ways...
RETURN 1
END SUBROUTINE TYPE151
Storage methods are not part of the language standard. Old FORTRAN compilers (FORTRAN 77 and earlier) frequently stored all variables statically. The language requires that you use "SAVE" for variables for which the values should be retained across calls to the procedure. But many programmers ignored this requirement and relied on the behavior that all variables retained their values because of the typical design of compilers in the FORTRAN 77 era.
Modern Fortran compilers typically use memory differently and local variables of procedures do not always retain their values if SAVE is omitted. This frequently causes bugs when old programs are compiled with current compilers. Compilers typically provide an option to restore the old behavior. Otherwise it could be a great deal of work to identify all variables in a large legacy program that needed to have the SAVE attribute added to their declaration.

Should External Routine Be Declared Always in Fortran?

In my Fortran code I made the following call to the dnrm2 routine:
d = dnrm2(n, ax, 1)
Just a simple call that would return me a double precision result.
The question is, should I declare the function at the start of my script? I found that if I don't declare it, when I compile the code in 32 bit Windows, then the result is correct.
But if I compile the code in 64 bit Windows, then the result isn't be correct.
Why is this so? Must an external routine always be declared in Fortran?
If you don't correctly describe your subprograms (subroutines and functions) to a calling program, the compiler may not correctly call them. Fortran compiles each unit separately, so the compiler doesn't "know", by default, about the characteristics of other subprograms. There are several ways that you can describe/declare a subprogram in Fortran 90/95/2003.
The easiest and best method is to place your subprograms into a module and then "use" that module in the calling program. This automatically makes the interface known to the compiler and will enable the compiler to check the consistency of actual arguments (in the call) and dummy arguments in the subprogram. It will also make known the return type of a function. The various subprograms in a module have their interfaces known to each other.
You can also write an "interface" containing a subprogram declaration that matches the declarations of the actual subprogram. (This method can be very similar to the style of including header files in C.) This method is more work and prone to error because you have to manually maintain consistency between the actual subprogram and interface whenever changes are made. The interface method is useful when you don't have the code to the subprogram or the subprogram is written in a language other than Fortran.
Or you can simply declare a function name to specify the type-return of the function, but this won't give you any checking of the arguments. In my opinion this method is weaker since having the compiler check argument consistency eliminates a major class of programming mistakes.
I don't do Fortran, but in C, the size of a pointer and the size of a long int varies between 32 and 64 bit OS'es, but the size of an int does not. Perhaps the program is using ints to do pointer arithmetic?