Is there ever a reason to write .eqv. .true.?

雨燕双飞 提交于 2019-12-10 17:47:16

问题


In logic, and in *ahem* properly designed programming languages, comparing a boolean to true is always redundant, i.e. a == True should be replaced by simply a. (And similarly, a == False by not a).

Many languages, including C, don't have a proper boolean type so it can make a difference whether you compare with true (e.g. 2 == true yields 0, which as a boolean represents false, while 2 itself can represent true).

Is this also an issue in Fortran, or can I always replace a .eqv. .true. by a?

(I found that in some legacy code, and I heavily suspect it's just one of the many things that the authors didn't really think through... but I'm curious whether there's actually some special case hidden there I should watch out for.)


回答1:


No, there is no reason to write that. a .eqv. .true. is the same as a. Just don't use ==, that is used for different data types.

Regarding things found in legacy codes, don't forget that many, if not most, Fortran users are not professional programmers and never received thorough training in proper programming techniques. Often, they were just taught the language rules.




回答2:


Is this really a pervasive issue?

since you asked "ever a reason" I can imagine using it as a placeholder during development/debugging:

 c if(a.eqv.b) .. 
   if(a.eqv..true.)

similarly I could see if someone modified code that originally had a as an integer and changed over to logical you might end up switching a.eq.1 to a.eqv..true. I can imagine if you have lots of complicated logical expressions this could be a safe/easy approach.

more obscurely you might use it to force a compile error in event a is not declared logical. (that would need to be in some usage that doesn't already need a logical, eg., as a subroutine argument, write statement, etc. )




回答3:


For a a logical type you do indeed, as previously stated, have a and a.eqv..true. being equivalent.

Inspired by agentp's answer where a.eqv..true. is a natural consequence of code development I'll give a perverse answer. This uses the operator .eqv. to force some form of test and that part is therefore not useless.

module tdef
  implicit none

  type t
    integer i
  end type

  interface operator (.eqv.)
    module procedure teqv
  end interface

 contains

  logical function teqv(a,b)
    type(t), intent(in) :: a
    logical, intent(in) :: b

    teqv = (a%i.eq.1).eqv.b
  end function teqv 

end module

use tdef
implicit none
print*, t(1), t(2), t(1).eqv..TRUE., t(2).eqv..TRUE.
end

There's a lesson here, as well as silliness: people do weird things. Always check carefully before replacing a.eqv..true. with a.



来源:https://stackoverflow.com/questions/29031603/is-there-ever-a-reason-to-write-eqv-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!