Anjan
Anjan

Reputation: 360

how can i swap value of two variables without third one in objective c

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,

Upvotes: 1

Views: 7166

Answers (5)

Bharrath
Bharrath

Reputation: 89

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);

Upvotes: 0

Arpit Agarwal
Arpit Agarwal

Reputation: 4003

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

Upvotes: 12

Rob Napier
Rob Napier

Reputation: 299355

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.

Upvotes: 1

Anomie
Anomie

Reputation: 94804

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.

Upvotes: 7

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31722

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"

Upvotes: 1

Related Questions