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.
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.
連結已複製
5 回應
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.
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.
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.
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.
[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]
