seymatinsar
seymatinsar

Reputation: 13

Incorrect values from common block

How can I create a link between routine and sub-program using Fortran?

Program Example

    common a,b,c,d,e
    print*,"Enter a"
          read*,a
    print*,"Enter coefficient of x in f1(x)"
          read*,b
    print*,"Enter intercept in f1(x)"
          read*,c
    print*,"Enter coefficient of x in f2(x)"
          read*,d
    print*,"Enter intercept in f2(x)"
          read*,e

    Print*,f1(2.),f2(3.)
    pause
    end
    !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function f1(x)
    common a,b,c
    f1=a*x**2+b*x+c
    return
    end
    !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    function f2(y)
    common d,e
    f2=d*y+e
    return
    end
    !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

this was an example. when I print the f1(2.) and f2(3.) I get true result for the first one and false results for the second one.

Upvotes: 0

Views: 177

Answers (1)

There are two very different questions in your post.

  1. How do we share data between subprograms? In modern Fortran use modules. We have many questions and answers about that. Common blocks are obsolete (and since Fortran 2018 officially obsolescent - Thanks @steve).

  2. Why are the results using common incorrect?

You are using an unnamed common block. In comon blocks the variable names are irrelevant. They can differ arbitrarily between compilation units (main program, subprograms). The order is important.

Therefore your

common d,e

is the same as doing

common a,b

To get access to the fifth element of the common block you must have all five variables

common a,b,c,d,e

(or as francescalus points out, one has to reference the right numerical storage unit. Ome could also have one array instead.)

Finally, I would like the stress the importance of implicit none. You should really use it.

Upvotes: 5

Related Questions