Reputation: 51
I have a fortran code using a derived type as follows:
if(type%value(1).LT.0D0 OR type%value(1).GT.1D0) then
if(type%value(1).LT.0D0) then
do something
end if
deallocate(type%value)
end if
In this scenario the statement type%value(1).LT.0D0
is checked twice. Is there a way to avoid this? More generally, is there a better approach to validate this?
Upvotes: 0
Views: 67
Reputation: 8140
Well, you have three paths:
type % value(1) < 0
type % value(1) > 1
0 <= type % value(1) <= 1
In all three paths the statements will be different, so you need two if
statements.
Do something
then deallocateHow you branch between the three paths is up to you, and the specifics of your code. The way you describe above is totally reasonable. If the evaluation is more computational intensive than a simple floating point comparison, it might be useful to store the results of this comparison in a logical variable, but other than that, it's fine.
Other ways are:
if (type % value(1) .LT. 0D0) then
do something
deallocate(type % value)
elseif (type % value(1) .GT. 1D0) then
deallocate(type % value)
end if
In a sense, this repeats the deallocate
statement, but it distinguishes the paths better. I'm testing this out, I don't know the exact Fortran Standard, but my understanding is that if the value is less than 0, then it is deallocated, but the elseif
isn't even tested, so it doesn't matter that it's no longer allocated at that point.
Ultimately, your method is fine. Make sure that the code is easy to read for you or whoever has to read the code in the future. I don't see any performance reason to chose one over the other.
Upvotes: 1