Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - Preserve bounds in allocation in intrinsic assignment

I am using automatic allocation on assignment to calculate the difference of two arrays, with bounds starting at 0:

program main
   implicit none
   integer, allocatable :: a(:), b(:), c(:)

   allocate(a(0:10))
   allocate(b(0:10))

   a = 1
   b = 2

   write (*,*) lbound(a)
   write (*,*) lbound(b)

   c = b - a

   write (*,*) lbound(c)
end program main

Both, gfortran and ifort give the output:

       0
       0
       1

Why doesn't c have the same bounds as a and b? Is there a short and concise (without an explicit allocate) way of making sure c has the same bounds?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Consider an intrinsic assignment statement where the left-hand side is not allocated and is an array:

variable = expr

In such a case, the array variable is allocated to the shape of the expression expr, with lower bound equal to the value of LBOUND(expr) (see Fortran 2018 10.2.1.3).

For the example of the question

c = b - a

the right-hand side is the expression b-a. For this expression LBOUND(b-a) is equal to 1: b-a is not a whole array (F2018 16.9.109). The lower bound of c on allocation is thus 1.

The only way the variable assigned to in intrinsic assignment with allocation to have lower bound not 1 is for the right-hand side to have lower bound not 1. In the assignment (c not allocated)

c = b

then c has lower bound that of b.

You could avoid an explicit allocate statement with

c = b
c = c - a

but that is rather unclear and (to repeat a point in Vladimir F's answer) would you want the lower bound to be that of b or a if these differ.

For completeness:

allocate(c(7:17), source=b-a)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...