模块或主程序数组在 Fortran 中必须具有恒定的形状错误 [英] Module or main program array must have constant shape error in Fortran

查看:48
本文介绍了模块或主程序数组在 Fortran 中必须具有恒定的形状错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模块中声明的一个整型变量作为全局变量来定义程序中相关数组的大小.程序的大小各不相同,因此数组的大小是变量而不是参数.它是在程序开始时确定的.

An integer variable declared in the module is used as a global variable to define the size of related arrays in the program. The size of program varies, so the size of array is a variable but not a parameter. It is determined at the beginning of the program.

在以下代码片段中,n 是全局大小变量.它在模块中声明并在主函数/程序的开头定义.n在主程序和主程序中包含的子程序类似的用法分别初始化一个数组.但是,主程序中的初始化会导致错误:模块或主程序数组必须具有常量形状错误,但子程序中的初始化有效.这种对不同位置使用的非常量值的不同处理背后的机制是什么?

In the following snippet of code, n is the global size variable. It is declared in the module and defined at the beginning of main function/program. Similar usage of n in the main program and the subroutine contained in the main program to initialise an array respectively. However, the initialisation in the main program causes the error: module or main program array must have constant shape error, but the initialisation in subroutine works. What is the mechanism behind this different treatment of non-constant values used in different positions?

module mod
  implicit none
  integer :: n
end module mod



program main
  use mod
  implicit none
  integer :: b(n)
  n = 5
  b(:) = 1
  print*, b(:)

  call sub

contains

  subroutine sub
    integer :: a(n)
    a = 10
    print*, a
  end subroutine sub

end program main

推荐答案

一个声明为 a(n) 的数组是一个 显式形状 数组.当 n 不是常量(命名或其他方式,严格来说是常量表达式)时,这样的数组是一个自动对象.

An array declared like a(n) is an explicit shape array. When n is not a constant (named or otherwise, strictly a constant expression) such an array is an automatic object.

自动对象的出现位置受到限制.特别是,显式形状数组受以下约束(F2008 的 C531):

Automatic objects are restricted in where they may appear. In particular, an explicit shape array is subject to the following constraint (C531 of F2008):

边界不是常量表达式的显式形状规范只能出现在子程序、派生类型定义、BLOCK 构造或接口主体中.

An explicit-shape-spec whose bounds are not constant expressions shall appear only in a subprogram, derived type definition, BLOCK construct, or interface body.

因为 n 来自模块 mod 不是一个常量,它不能在主程序中用作数组的边界.子程序 sub 是一个子程序,所以 a(n) 是非常量边界的有效使用.

As n from the module mod is not a constant it cannot be used as bounds of an array in the main program. The subroutine sub is a subprogram and so a(n) is a valid use of a non-constant bound.

与其在主程序中使用自动对象,不如考虑使用pointerallocatable 属性的延迟形状 数组.

Instead of having an automatic object in the main program, one can instead consider deferred shape arrays, using either pointer or allocatable attributes.

这篇关于模块或主程序数组在 Fortran 中必须具有恒定的形状错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆