hey guys i want your suggestion that how can change value of two variables without 3rd one. in objective cc. is there any way so please inform me,
-
3Your question does not make any sense. Please provide more information. – Anurag Mar 10 '11 at 03:01
-
hey Mr. anurag i want to chage two variables value with each other without using 3 variable(extra variable) in objective c. so do u have any idea about it – Anjan Mar 10 '11 at 03:13
-
this is called "swap variables" – Max Mar 10 '11 at 03:31
-
Don't do this.... but you can achieve it with this: `a^=b^=a^=b;` – Albert Renshaw Feb 12 '21 at 07:54
5 Answers
it can be done in any language. x and y are 2 variables and we want to swap them
{
//lets say x , y are 1 ,2
x = x + y; // 1+2 =3
y = x - y; // 3 -2 = 1
x = x -y; // 3-1 = 2;
}
you can use these equation in any language to achieve this

- 3,993
- 24
- 30
-
1+1, Simple logic for swaping two variables without using third one. logic is one you can implement in any language – Ishu Mar 10 '11 at 04:16
-
What's interesting is that it even works if x+y overflows x, provided the operation "wraps around" in that case, which is common. That makes it attractive on micro-controllers where registers and RAM are scarce and accessing RAM can be expensive (possibly more expensive than three register arithmetic operations). Nice. I'd never use it in Objective C, but still, nice. (XOR swap is probably still more efficient, but I like this.) – Rob Napier Aug 01 '11 at 15:47
Do you mean exchange the value of two variables, as in the XOR swap algorithm? Unless you're trying to answer a pointless interview question, programming in assembly language, or competing in the IOCCC, don't bother. A good optimizing compiler will probably handle the standard tmp = a; a = b; b = tmp;
better than whatever trick you might come up with.
If you are doing one of those things (or are just curious), see the Wikipedia article for more info.

- 92,546
- 13
- 126
- 145
As far as number is concerned you can swap numbers in any language without using the third one whether it's java, objective-C OR C/C++,
For more info
Potential Problem in "Swapping values of two variables without using a third variable"

- 1
- 1

- 31,697
- 9
- 72
- 76
Since this is explicitly for iPhone, you can use the ARM instruction SWP, but it's almost inconceivable why you'd want to. The complier is much, much better at this kind of optimization. If you just want to avoid the temporary variable in code, write an inline function to handle it. The compiler will optimize it away if it can be done more efficiently.

- 286,113
- 34
- 456
- 610
NSString * first = @"bharath"; NSString * second = @"raj";
first = [NSString stringWithFormat:@"%@%@",first,second];
NSRange needleRange = NSMakeRange(0,
first.length - second.length);
second = [first substringWithRange:needleRange];
first = [first substringFromIndex:second.length];
NSLog(@"first---> %@, Second---> %@",first,second);

- 79
- 1
- 5