Jump to content

Swapping variables


Recommended Posts

My question is about a particular method of swapping variables.

$x -= $y
$y += $x
$x = $y - $x

My question involves the last line.

$x is subtracted from $y and then the result is stored back into $x.

In order to store the result back into $x then wouldn't there need to be a variable to store the result temporarily?

Otherwise the result would be lost right.?

Link to comment
Share on other sites

Nope, I often use a variable in the same line as I redefine it to no ill effect. For instance, when I'm working with names I can do something like the following:

$name="squid808"
$name=stringtrimright($name,stringlen($name)-2)
msgbox(0,"Hi","The first two letters of my SN are " & $name)

You don't have to worry about having a temporary or swap variable to hold on to things.

Link to comment
Share on other sites

Those variables are memory locations. What happens is, when you perform a calculation, the instruction for the operation is loaded into the CPU with all its flags and registers. After the calculation is performed, the result is then stored into whatever memory location is referenced by the variable.

So in essence, the CPU will be temporarily holding on to the result so there's nothing stopping you from storing the result in the same memory location as one of the parameters used for the calculation.

Edited by omikron48
Link to comment
Share on other sites

I'm thinking behind the scenes here like what would the compiler do? ... wwcd ...

There is no compiler. This is an interpreted language. The .exe is an illusion just containing the source and interpreter with instructions on what to do.

Link to comment
Share on other sites

Those variables are memory locations. What happens is, when you perform a calculation, the instruction for the operation is loaded into the CPU with all its flags and registers. After the calculation is performed, the result is then stored into whatever memory location is referenced by the variable.

So in essence, the CPU will be temporarily holding on to the result so there's nothing stopping you from storing the result in the same memory location as one of the parameters used for the calculation.

Ok, so it would take two or three registers?

There is no compiler. This is an interpreted language. The .exe is an illusion just containing the source and interpreter with instructions on what to do.

I never knew that! thanks

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...