Yotam
Yotam

Reputation: 10685

Why would common block variables not preserve their values?

First, I know that using common blocks is a bad idea in fortran (and programming in general). However, I'm updating someone else's code and I don't want to mess up things that are known to work.
Second, I know I should post something more specific then this. If I knew how to reduce this into something small, I would. However, since I know, and I don't think you'll appreciate 2500 lines of code, I can't post a specific example.
With that in mind, I can't describe my problem.

I'm updating someone else's fortran code. The guy used several (4) common blocks to set up global variables. For some reason when I call a function that use such a block, all it's value are 0. Has anyone encountered that before? Does anyone know why this might happen? How to reproduce this? Any starting point to check this would be helpful.

For what it worth, the said common block is declared as

common /set/ block,x,y,z,llx,lly,llz,ilx,ily,ilz,third,third2

block is a 4D array. x, y, and z are 1D array. llx,lly, and llz, are double precision types. The rest are integer types.

The common block(s) is (are) declared and initialized at the main program before any function is called.

Upvotes: 4

Views: 2101

Answers (2)

Miguel
Miguel

Reputation: 1363

Can you compare your code with this tiny example? I think you might be missing something, like the "common" declaration inside the subroutine.

Note that you don't need to use the same name for the variable inside the subroutine (AA) as you have for main (GB). Just the common block name (myarray) has to be the same. However, nothing bad will happen if you replace AA by GB, and the final result would be a little bit cleaner to read.

program main
    real             GB(4)
    common /myarray/ GB

    integer  i
    real     B(4)

    GB=0
    write(*,*) 'GB',GB

    do i=1,4
        call AddSubR()
        write(*,*) 'GB',GB
    enddo

end program main

subroutine AddSubR()
    real             AA(4)
    common /myarray/ AA

    integer i

    do i=1,4
        AA(i) = AA(i)+1
    enddo

end subroutine AddSubR

Upvotes: 1

Bálint Aradi
Bálint Aradi

Reputation: 3812

Some compilers do initialize common variables to zero, so if you first invoke the function with the common block, you might find zeros everywhere (although you should not rely on that). But once you set some values for the common block variables in the program, those values should appear whenever you use the common block.

As of the variables in the common block: They can be of arbitrary type, as long as they are consistently defined at all places, where the common block is used.

Upvotes: 2

Related Questions