Re: Swapping Variables (without a temp variable) by Ross
Ross
Sun Jun 06 21:50:34 CDT 2004
Scott McNair <scott.mcnair@sfmco.takethispartout.com> wrote in
news:Xns94F58603A7758sfmco@207.46.248.16:
> Normally at work whenever we want to swap the value of two variables,
we
> use code similar to the following:
>
> Dim TempVar
> TempVar = VariableX
> VariableX = VariableY
> VariableY = TempVar
>
> Is there anything out there that will do this in an elegant, one-line
> approach?
>
> e.g.: Swap(VariableX,VariableY)
>
> I realize you could probably build a function easy enough but I don't
> want to recreate the wheel if I don't have to.
>
> Cheers,
> Scott
Well, it ain't elegant and it ain't one-line, but if you know your
variables contain strings, this can avoid the extra temp variable:
VariableY = VariableY & VariableX
VariableX = left(VariableY, len(VariableY) - len(VariableX))
VariableY = mid(VariableY, len(VariableX)+1)
Or, if you know your variables contain integers, you can use XOR to avoid
the extra temp variable:
X = X XOR Y
Y = X XOR Y
X = X XOR Y