fortranintel-fortranreal-datatypetype-equivalence

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 ?


Solution

  • 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.