Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
27428 Discussions

Can an integer member of a user-defined type be used as a do-loop index?

avinashs
New Contributor I
193 Views

I have a user-defined variable that contains an integer component that I want to use as an index for a do-loop. However, this generates the error

Error error #5082: Syntax error, found '%' when expecting one of: =
 
The following is the code fragment:
 
  type :: myvar
     integer(kind = 4) :: i
  end type myvar

  type(myvar) :: a

  do a%i = 1,10
     ! body of loop
  end do
  read *

Does it mean that the use of a%i as an index is illegal or is the compiler not setup to recognize the %.

0 Kudos
4 Replies
Steve_Lionel
Black Belt Retired Employee
193 Views

It's not valid in the language. Can't use an array element either. The standard says that the do-variable must be a "scalar-int-variable-name" - the "name" means that it has to be a variable name and not a component or element or anything other than an unadorned name.

FortranFan
Honored Contributor II
193 Views

@avinashs,

From what I can see in the Fortran standard text though, there is nothing that precludes the use of ASSOCIATE construct toward your end, the associating entity is a variable with the same rank as the selector (which is a scalar in your case) and said entity is definable if the selector is, again which is true in your case:

   type :: myvar
      integer(kind = 4) :: i
   end type myvar

   type(myvar) :: a

   associate ( i => a%i )
      do i = 1, 10
         ! body of loop
      end do
   end associate

 

jimdempseyatthecove
Black Belt
193 Views

While FF's insight may be correct (i.e. loophole in specification), I would caution that it is undefined as to if at the end of the associate, that a%i would be updated to the final value of the (presumably) compiler locally optimized i.

Jim Dempsey

avinashs
New Contributor I
193 Views

Thanks everyone for the useful suggestions. Since using an integer component of a structure is invalid syntax, I intend to use the loop index as follows so that it can be used as a global variable.

a%i = 0
do
   a%i = a%i + 1
   if (a%i > 10) exit
   ! calculations go here
end do

 

Reply