smog
smog

Reputation: 51

How to avoid repeated checking of an if-statement when the condition to be checked is deallocated within the if-block?

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

Answers (1)

chw21
chw21

Reputation: 8140

Well, you have three paths:

  1. type % value(1) < 0
  2. type % value(1) > 1
  3. 0 <= type % value(1) <= 1

In all three paths the statements will be different, so you need two if statements.

  1. Do something then deallocate
  2. Only deallocate
  3. Nothing

How 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

Related Questions