I understand that two variables, say a1 and a2 appear in Equivalence(a1,a2) statement in Fortran, then they occupy the same memory space. So say this happens in a procedure where both a1 and a2 are local variables in that procedure.

This means that you can't only have a copy of a1 and a2 in memory right? Because one of the values will be overwritten. You could keep a1 in the memory location and keep a2 in a register for the whole of the procedure and this will be fine right?

My question is basically: Can you keep a1 in a register for the whole procedure?

I would say yes...unless you run out of registers and a1 has to be stored back to memory. Then you will overwrite a2 and lose it's value, and both variables a1 and a2 will then actually point to the value of a1.

有帮助吗?

解决方案

a1 and a2 in an equivalence statement means that those two variables will occupy the same storage. Changing one will alter the other, even if they are variables of different types (e.g., a1 is an integer and a2 is a real.). Fortran doesn't give you any way to specify that a variable should be in a register and it seems extremely likely that an equivalence statement will inhibit the compiler doing so automatically.

So

You could keep a1 in the memory location and keep a2 in a register for the whole of the procedure and this will be fine right?

is inapplicable.

I strongly recommend against the use of equivalence ... it is pernicious and likely only retained in the language to support legacy code. If you have the need to transfer data across types, the modern Fortran method is the transfer intrinsic.

其他提示

The only reason to use equivalence is to have two names for the same thing. As a fortran programmer, you can't control the registers or any such thing. Don't think about memory and registers. Think that you have one 'box' with two names. Whichever name you use, you are storing into or retrieving from the same box.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top