Community
cancel
Showing results for 
Search instead for 
Did you mean: 
New Contributor I
28 Views

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

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
Highlighted
Black Belt Retired Employee
28 Views

It's not valid in the

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.

--
Steve (aka "Doctor Fortran") - https://stevelionel.com/drfortran
0 Kudos
Highlighted
Valued Contributor III
28 Views

@avinashs,

@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
Highlighted
28 Views

While FF's insight may be

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
Highlighted
New Contributor I
28 Views

Thanks everyone for the

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