假设我有一个子例程:
subroutine foo(x, Nx) implicit none integer, intent(IN) :: x integer, intent(IN) :: Nx select case(x) case (1) write(*,*) "Minimum value" case (Nx) write(*,*) "Maximum value" case default write(*,*) "Somewhere in-between" end select end subroutine foo假设我的驱动程序看起来像这样:
Suppose my driver looks like this:
program main implicit none interface subroutine foo(x,Nx) integer, intent(IN) :: x integer, intent(IN) :: Nx end subroutine foo end interface integer, parameter :: Nx = 100 integer :: x call foo(20, Nx) end program main上面的程序将无法编译,因为在子例程中,case (Nx)无效.具体来说,ifort 16会出现以下错误:
The above program will not compile because in the subroutine, case (Nx) is invalid. Specifically, ifort 16 gives the following error:
错误#6601:在CASE语句中,case值必须是一个常量表达式.
error #6601: In a CASE statement, the case-value must be a constant expression.
换句话说,即使通过intent(IN)有效地将Nx声明为子例程常量,它也必须是文字常量或类型为integer的parameter.
In other words, even though Nx is effectively declared as a subroutine constant via intent(IN), it needs to be either a literal constant or parameter of type integer.
是否有任何方法可以使case语句接受Nx作为我们知道的常量参数?有什么方法可以将Nx声明为传入的parameter吗?
Are there any ways to make the case statement accept Nx as the constant parameter we know it to be? Is there some way to declare Nx to be a passed-in parameter?
我意识到在这个简单的简短示例中,if-then-elseif-else-end块就足够了,但是我不知道这个问题的答案. :-)
I realize that in this simple, short example, an if-then-elseif-else-end block would suffice, but then I wouldn't know the answer to this question. :-)
推荐答案只需使用if语句.子例程参数(您称为参数)当然不是参数(命名为常量). intent(in)不能有效地使其成为 参数,这只是一个承诺,您不会更改它,但是有一些方法可以绕开它. case语句需要一个编译时常量.
Just use an if statement. A subroutine argument (which you call parameter) is certainly not a parameter (named constant). The intent(in) doesn't make it effectively a parameter, it is just a promise you will not change it, but there are ways to circumvent that. The case statement needs a compile-time constant.
更多推荐
将参数作为参数传递给Fortran
发布评论