Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How I can swap between value variables using two variables only?

user-image
Question added by ehab ab'oushi , IT Manager , INGOT Brokers
Date Posted: 2013/06/25
Daanish Rumani
by Daanish Rumani , Product Manager , Publicis Sapient

Let a and b be the two variables.
// Swap a and b a = a + b; b = a - b; a = a - b; Example Assume a =12, b =7 a = a + b; // a =19, b =7 b = a - b; // a =19, b =12 a = a - b; // a =7, b =12 But you should use a third variable when swapping.
The above method fails when a and b are float or double.
Also it cannot swap values whose addition is more that the max supported value.
i.e.
a + b > Int.Max for int type.