Quoted from LitusSaxonicum
There is nothing intrinsically wrong with having undefined values in any variable, but if you actually use those values in any conventional sort of arithmetic, you don't have a clue as to what the result will be snip
The result will be undefined but you might not realise it 😃
I try to define only the variables I need in a particular scope and leave all the other variables that are in scope undefined. This way, if I make a mistake and reference one of the undefined varables in an expression, the run-time checking (/CHECKMATE) will show me my error.
For debugging, I also put a call in the program to explicitly undefine variables that should not be referenced, e.g.
call set_undefined(a)
call set_undefined(b)
where set_undefined is simply
subroutine set_undefined(var)
real, intent(out) :: var !< make var undefined using /CHECKMATE
end subroutine set_undefined
I actually have a collection of set_undefined in a module with one generic INTERFACE to handle all variable types and kinds.
In the following loop, a and tmp do not need to be carried from one loop iteration to the next, so are made undefined.
s = 0.0
do i=1, 100
! lose values when loop is entered and at last iteration
! comment out in production code.
call set_undefine(a)
call set_undefine(tmp)
! Inadvertant reference of a or tmp here will give an error
a = real(i)
tmp = a**2 ! An error would occur here if i forgot to define a
s = s + tmp ! An error would occur here if i forgot to define tmp
end do
This is extra work, but it helps to document the code and saves time during debugging.