Statement of equivalence

code:

program CheckEquivalence integer*8 intarray(4) real*8 realarray(4) equivalence(realarray,intarray) realarray(3) = 3 intarray(4) = 4 realarray(1) = 1.0 realarray(2) = 2.0 do i = 1,4 write(,) 'All real ', realarray(i) enddo do i = 1,4 write(,) 'All int ', intarray(i) enddo do i = 1,3 write(,) 'Some real ', realarray(i) enddo write(,) 'Last int ', intarray(4) end 

:

 All real 1. All real 2. All real 3. All real 1.97626258E-323 All int 4607182418800017408 All int 4611686018427387904 All int 4613937818241073152 All int 4 Some real 1. Some real 2. Some real 3. Last int 4 

I tried one example code to understand how equivalence works. My request is in what format is the internal data stored and any algorithm from which I can get the theoretical value?

+4
source share
2 answers

As indicated here:

fortran equivalence statements

There is no conversion between these two values. It is stored based on what you write to the variable and interpret based on how you access it. Therefore, if you write a real value in REAL , and then try to print an integer variable, you will get garbage. And vice versa.

Generally speaking, do not use EQUIVALENCE expressions. They are a bad idea and outdated. If you are writing new code, do not paste them - if you are trying to interpret old code, they are usually used to create compact storage in memory by reusing the same location for different purposes.

+6
source

Yes, as has already been said, there is very little reason to use EQUIVALENCE. It was used several decades ago to preserve memory with overlapping arrays. It can also be used for low-level intolerable manipulations. If you store the real number and output it as an integer, the results will not be portable, outside the standard language, depending on the numerical representation of the equipment used. There are random reasons for doing bit-level manipulations, for example, if you read in binary data and then determine what type it is. Or do a byte replacement. The modern replacement for EQUIVALENCE is the "transfer" internal function.

+1
source

Source: https://habr.com/ru/post/1387303/


All Articles