Scope of variables in case of modules used by modules in Fortran

前端 未结 3 858
名媛妹妹
名媛妹妹 2021-01-21 01:17

I\'ve noticed that variables in a (child) module, which are used by a parent modules are accessible in a main program through just the parent module. This is one concept which c

3条回答
  •  鱼传尺愫
    2021-01-21 01:48

    The best thing to do, in my opinion, is to avoid the use of blanket use statements, especially for large and sometimes unwieldy modules. Instead, specify which module entities to inherit via the only keyword, such as:

    program main
       use a_mod, only : c, inc_c
       implicit none
    
       call inc_c
       write(*,*) c
    end program main
    

    This works, but it's confusing because a_mod isn't the real owner of c and inc_c. Therefore, you should try to use entities from where they are actually declared, which gives:

    program main
       use c_mod, only : c, inc_c
       !   ^ This has changed
       implicit none
    
       call inc_c
       write(*,*) c
    end program main
    

    Now, anybody reading the code has a clear notion of which variables and subroutines are in scope and where they come from.

    Finally, this has the added benefit of reducing the risk that you use c without realizing it's actually inhereted from c_mod. This is particularly a problem when not using implicit none!

提交回复
热议问题