Home Ask Login Register

Developers Planet

Your answer is one click away!

Foredoomed 2 weeks ago

How to explain swap two integers without using a third variable

I found the following code to swap two integers without a third variable:

a=b+(b=a)*0

Can anyone explain it in details? Thanks in advance.

Answers


Mena 2 weeks ago

Let's analyze it bit by bit.

  • Start with (b=a), is the first operation performed due to the parenthesis, and assigns b with a's value
  • That expression is multiplied by 0 (next priority operation)
  • It is then added to b inline (so a = [old reference to b] + 0)
  • And there you have it


nullpointer 2 weeks ago

I am not sure, if this could go as a community post as well:

a=b+(b=a)*0

=> a = b + 0 //eventually, so a would become b

=> a = b + (b=a) * 0 // basically assign existing value of a to b here

The crux is using the existing values, since if the expression would be split into multiple statements, chances are using their updated values in the evaluation.


corsiKa 2 weeks ago

When you assign a variable, you also return that variable as the result.

a=b+(b=a)*0

We're assigning a some value. What is this value? Well, it's b + (some quantity) * 0. Anything times 0 is 0, so we know that this point a = b.

In the mean time, in the middle there, we're assigning b = a. These are the swaps that count. And because we put the b on the stack before the (b=a) that b is saved.

So in short it does use a temporary variable, if you think about it. It pushes b on the stack.

Post Status

Asked in 2 weeks ago
Viewed 3,925 times
Voted 12
Answered 3 times

Search




Leave an answer


Quote of the day: live life