Search code examples
fortranblockfortran-common-block

Common Blocks in Fortran


Does Fortran have common blocks in common blocks? Like there are structs within structs. E.g.

integer int 1, int2
common/Common1/int1, int2
float f1, f2
common/Common2/f1, f2
save/Common2/, /Common1/

Does the above code mean that common2, in within common1?


Solution

  • No, the code you wrote is invalid. A common block is simply a named region of memory.

    Fortran has "derived data types" that are very similar to C structs. A Fortran derived type declaration looks like this:

    type float_struct
      real :: f1, f2
    end type
    

    Now you can declare another derived type that contains a variable of this type:

    type my_struct
      integer :: int1, int2
      type (float_struct) :: my_float_struct
    end type
    

    Note that these are declarations of a type, not instantiations of a variable of that type. It is best to put the declarations in a module, allowing you to access them in a subroutine, function, or program. For example, suppose the declarations above are placed in a module named "my_structs_mod". Then you can use them like this:

    subroutine sub()
    use my_structs_mod
    type (my_struct) :: ms
    ms%int1 = 42
    ...
    end subroutine
    

    Note that the percent sign (%) is similar to the dot (.) operator in C. It allows you to access the data contained in a derived type.