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

查看:212
本文介绍了模块或主程序数组在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.

由于模块mod中的n不是常量,因此不能用作主程序中数组的边界.子例程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天全站免登陆