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

Increment values regarding counting do loops.

macmcmonkey
Beginner
811 Views
Just a quick query.

Does anybody know if I can use the same variable e.g. 'i',throughout a program or does the increment variable have to be a different letter for each loop.

I know this is a simple question but it will save me a lot of time if i know before i try to build the program. Any help is welcome.
0 Kudos
5 Replies
anthonyrichards
New Contributor III
811 Views
You can re-use it as many times as you want, provided that, for each loop, the loop variable value only has relevance within the loop body. Never assume a loop index value is preserved outside a loop.
0 Kudos
macmcmonkey
Beginner
811 Views
Thank you very much for the advice. Yes the increment value never has relevance outside of a loop so that should be fine.

Thanks for your fast responce you have saved me a lot of un-needed hastle.
0 Kudos
TimP
Honored Contributor III
811 Views
If you do need to use the loop index after or while exiting the loop, it probably helps readability to have a specific name. The values of loop index after exit became standardized in f77 and compilers have implemented it correctly for 20 years.
Many years ago, back in the days of compilers with everything SAVEd, there were cases where re-using a variable name would inhibit optimization, but I haven't seen this problem with any compiler available in the last decade.
0 Kudos
Steven_L_Intel1
Employee
811 Views
By the way, you asked about "the same letter". While I is a very common choice for a DO loop control variable, it can be any variable name (which in Fortran 2003 can be up to 63 characters long and can contain digits and underscores), as long as it is typed INTEGER. There's no requirement that it be a single letter.
0 Kudos
JVanB
Valued Contributor II
811 Views
[bash]! I assume you ask because you wish to make the following
! error, which always uses the variable i!
program start
   integer i,j
   j = 0
   do i = 1, 10
      call sub
      j = j+1
   end do
   write(*,*) j
   contains
      subroutine sub
         do i = 1, 3
         end do
      end subroutine sub
end program start
[/bash]
0 Kudos
Reply