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

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

avinashs
New Contributor I
386 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
Honored Contributor III
386 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.

0 Kudos
FortranFan
Honored Contributor II
386 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

 

0 Kudos
jimdempseyatthecove
Honored Contributor III
386 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

0 Kudos
avinashs
New Contributor I
386 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

 

0 Kudos
Reply