Problems May Occur When Passing the Same Array Element Twice (66455)






This article was previously published under Q66455

SUMMARY

The following program may give unexpected results when the same array element is passed twice to the subprogram. The problem results from a form of variable aliasing, where the same memory location is referenced by two different variables.

To avoid aliasing problems, never pass the same variable twice in a given parameter list.

MORE INFORMATION

Passing the same array element twice in the same parameter list can give incorrect or unexpected results regardless of array type or dynamic or static array allocation. The results may also vary between compiler versions. A customer reported that the program below gave the results that he wanted in QuickBasic 4.00, but not in Microsoft Basic Professional Development System (PDS) version 7.10; Microsoft has not confirmed this report.

This behavior results from the fact the Basic often requires a far pointer to access arrays, but parameters need to be passed as near pointers. On a CALL, Basic sets aside a temporary location holding the array element and then passes a pointer to the temporary area.

There are two options in this sort of situation: Recode the subprogram so that it is not necessary to pass the array element twice, or assign one of the parameters to a temporary variable and then pass the temporary variable.

REFERENCES

For a similar article on variable aliasing when a parameter is both SHARED and passed as a parameter to a subprogram, query in this Knowledge Base on the following words:

DYNAMIC and ARRAY and ALIASES

A variable should not be passed twice in the list of arguments passed to a procedure; otherwise, variable-aliasing problems will occur. This restriction is documented under "The Problem of Variable Aliasing" on Page 64 in the "Microsoft Basic 7.0: Programmer's Guide" for Basic PDS versions 7.00 and 7.10, on Page 68 of the "Microsoft QuickBasic 4.5: Programming in Basic" manual, and on Page 78 of the "Microsoft QuickBasic 4.0: Programming in Basic: Selected Topics" manual for QuickBasic versions 4.00 and 4.00b.

Code Example

   DECLARE SUB MakeUpper(instring AS STRING, outstring AS STRING)
   DIM a$(15)
   a$(4)="abcdefg"
   CALL MakeUpper(a$(4), a$(4))
   PRINT a$(4)
   END

   SUB MakeUpper(instring AS STRING, outstring AS STRING)
     outstring = UCASE$(instring)
   END SUB
				

Modification Type: Minor Last Reviewed: 1/9/2003
Keywords: KB66455