DIMension in a FOR-NEXT Loop Is Possible (61440)



The information in this article applies to:

  • Microsoft QuickBASIC 4.0
  • Microsoft QuickBASIC 4.0b
  • Microsoft QuickBASIC 4.5
  • Microsoft Basic Professional Development System for MS-DOS 7.0
  • Microsoft BASIC Compiler for MS-DOS and OS/2 6.0
  • Microsoft BASIC Compiler for MS-DOS and OS/2 6.0b

This article was previously published under Q61440

SUMMARY

Microsoft QuickBasic allows you to correctly DIMension a static array within a loop (FOR, WHILE, or DO). This is possible because a DIM of a static array happens as the program is being compiled (or during the binding phase in the interpreter). DIM on a static array is not an executable statement. Even though the DIM appears in a loop, it is not being executed over and over as the loop iterates. Each time the loop executes, the array is not being redimensioned. Therefore, any values inserted into the array are not lost.

This information applies to Microsoft QuickBasic versions 4.00, 4.00b, and 4.50, to Microsoft Basic Compiler versions 6.00 and 6.00b, and to Microsoft Basic Professional Development System (PDS) version 7.00.

MORE INFORMATION

The situation is different for dynamic arrays. QuickBasic will give you an error on a DIMension of a dynamic array in a loop. If an array needs to be redimensioned as a loop executes, the program should REDIM the array in the loop. REDIM is an executable statement, and therefore, will be executed over and over as the loop repeats. As the loop executes, REDIM will reallocate the memory for that array and erase its previous contents.

The following code example demonstrates this feature of Basic:
c% = 100
FOR i% = 1 TO 20
'  DIM a%(c%)   ' will generate an error.
'  REDIM a%(c%) ' will redim the array and erase its contents.
   DIM a%(20)
   a%(i%)=i%
   PRINT a%(i%)
NEXT i%

FOR j% = 1 TO 20
   PRINT a%(j%)
NEXT j%
				

Modification Type:MinorLast Reviewed:8/16/2005
Keywords:KB61440