Swap 2 number without using third variable

code do not use temp variable for swapping

if the code was useful please let me know

#include <stdio.h>
void main()
{
int a,b;
printf("enter number1: ie a");
scanf("%d",a);
printf("enter number2:ie b ");
scanf("%d",b);
printf(value of a and b before swapping  is a=%d,b=%d"a,b);
a=a+b;
b=a-b;
a=a-b;
printf(value of a and b after swapping  is a=%d,b=%d"a,b);
}

Edited 5 Years Ago by peter_budo: Changing to discussion thread as code snippet is getting negative attention

Comments
Load of rubbish - learn about integer overflow

just a tricky way

#define SWAP(a, b)  do { a ^= b; b ^= a; a ^= b; } while ( 0 )

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Comments
Just a useless way riddled with undefined behaviour
Gud1

this can be done using stack...........put the value of a and b in stack....then store first in b then in a.... as stack is first in last out....

For a newbie Zamansiz, you certainly have my vote of confidence.
-
Using 'tricks' and 'trickly subrt'ns is exactly what got Microsoft into so many buggy problems at the beginning.

- You are spot-on by laying this out in the beginning
and allowing the debugger see it right away.

- - Easy to spot - Easy to understand.

Shift-Stop

* by Newbie I am assuming that you're
New to coding
and not Ken Thompson, or D. Ritchie, or K. Knowlton.

Edited 6 Years Ago by Shift-Stop: scrambled keys

#include<stdio.h>
void main()
 {
   int a=10,b=20;
   printf("Variables Before swap\nA= %d \nB= %d",a,b);
   a=a+b;
   b=a-b;
   a=a-b;
   printf("\nVariables after swap\nA= %d \nB= %d\n",a,b);
 }
#include<stdio.h>
void main()
 { 
   int a=10,b=20;
   printf("Variables Before swap\nA= %d \nB= %d",a,b);
   a=a*b;
   b=a/b;
   a=a/b;
   printf("\nVariables after swap\nA= %d \nB= %d\n",a,b);
 }
#include<stdio.h>
void main()
 {
   int a=10,b=20;
   printf("Variables Before swap\nA= %d \nB= %d",a,b);
   a^=b;
   b^=a;
   a^=b;
   printf("\nVariables after swap\nA= %d \nB= %d\n",a,b);
 }
Comments
Load of rubbish - learn about integer overflow

Method1
(The XOR trick) a ^= b ^= a ^= b;
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will also not work for floating-point values. Also, think of a scenario where you have written your code like this

swap(int *a, int *b)
{
*a ^= *b ^= *a ^= *b;
}
Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other. swap(int *a, int *b) {
if(*a!=*b) { *a ^= *b ^= *a ^= *b; } }

Method2 This method is also quite popular a=a+b; b=a-b; a=a-b; But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results. Method3 One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro which looks something like this
#define swap(type,a,b) type temp;temp=a;a=b;b=temp;
Now, think what happens if you pass in something like this swap(int,temp,a) //You have a variable called "temp" (which is quite possible). This is how it gets replaced by the macro
int temp;
temp=temp;
temp=b;
b=temp;
Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it? So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary variable. Its not only fool proof, but also easier to understand and maintain.

Comments
nicely put

haii this code also works to swap two numbers


if a=5,b=4
then a=(a+b)-(b=a);
also works

Comments
Highly compiler dependent, if b = a executes first then it will give wrong answer.
Load of rubbish - learn about integer overflow

it can be like this

#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
printf("enter the two variables:");
scanf("%d%d",&i,&j);
printf("before swap:First Var.=%d\tSecond Var.=%d\n",i,j);
i=i+j;
j=-(j-i);
i=-(i-j);
printf("After Swap: First Var.=%d\tSecond Var,=%d\n",i,j);
getch();
return 0;
}

Edited 5 Years Ago by peter_budo: Keep It Clear - Do wrap your programming code blocks within [code] ... [/code] tags

Comments
Load of rubbish - learn about integer overflow

Crucify me if you like, but the simple answer is that you can't. Even the CPU's XCHG instruction uses a hidden TEMP. Yes, there are lots of tricks and kludges that get you most of the way there, but they ALL fail on some type of data or other. Besides, why in the world would anyone want the use additions, subtraction, multiplications and divisions (inefficient) rather than a simple MOVE instruction (very efficient) and suffer all the ills of truncation and round-off error? It's slower, uses more memory and is failure prone. On the other hand, creating a temp is either a Zero time operation (created at compile time) or a very fast creation on the Stack (one assembly instruction). Iven if the Temp needs to be created on the heap or in thread local storage, it's still probably faster. If you really need to optimize, the only guaranteed method is to use assembly - and even that may have issues of transportability. The only time I would ever consider this would be when swapping giant structures (or perhaps millions of small ones), and even then I would probably re-write the code model to use pointer swaps instead. Why move big chunks of data when you can simply swap a pointer?

Want a simple assembly language example?

Mov ECX, SizeOfVariableInBytes
Mov SI, AddressOfOneObject
Mov DI, AddressOfOtherObject

MLP:
    Mov AL,[ESI]
    Mov AH,[EDI]
    Mov [ESI],AH
    Mov [EDI],AL
    Inc ESI
    INC EDI
    Loop MLP

This is an untested skeleton, just showing the essentials. It is written in terms of bytes simply because it is bad technique to write an generic example for a certain data type in particular. It also assumes the use of 32 bit registers, and that the data is in the (default) Data Segment. It will only work with simple data types and structure, but will fail miserably on things like Class Instances.

If you are really a Hog for optimization, you could shorten it to this:

    Mov ECX, SizeOfVariableInBytes
    Mov SI, AddressOfOneObject
    Mov DI, AddressOfOtherObject

    MLP:
        Mov AL,[ESI]
        XCHG AL,[EDI]
        Mov [ESI],AL
        Inc ESI
        INC EDI
        Loop MLP

Which uses the EXCH instruction to replace a pair of Mov Instructions. My opinion is that no optimizing compiler can do better than this, except perhaps when possible by moving words or double words and therefore fewer loop iterations. In fact, something like this is probably what the compiler would construct anyway.

#include<conio.h>
#include<stdio.h>

void Change_Address( int *&p, int *&pt)
{
     int *pp;
     pp = p;
     p = pt;
     pt= pp;
}
int main(void)
{
    int a =3, b = 4, *p, *p1;
    p = &a; p1 = &b;    
    printf("%d %d\n", *p, *p1);
    Change_Address(p, p1);
    printf("%d %d", *p, *p1);

    getch();     
    return 0;
}
Comments
what's the use of *&??

Thanks for all of your answers..... But i have one doubt.
While swapping if overflow occurs how to manage it....?
Or else if any other solution is there to take care overflow also.

While swapping if overflow occurs how to manage it....?

Use a temporary variable of the same type, no overflow will occur in that situation. If you try using the arithmetic tricks, overflow is a risk and greatly increases the complexity of the swap for the negligible benefit of a few bytes saved memory. If you try using the XOR swap, swapping with self is a risk and slightly increases the complexity of the swap. XOR also demands that the swapped type be integral.

These tricks put undue restrictions on you, and the savings aren't worth it if you're writing a general purpose swap. So the answer is to just bite the bullet and use a temporary variable; they're not that expensive.

Don't try to be clever, write code that works.

Comments
That's why using temp variable is always safest..good point
Good point!

These are applicable to programming in general (Python -> import this)

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Edited 2 Years Ago by pyTony

import java.io.*;
class swap{
        public static void main(String args[]) throws IOException{
            BufferedReader br=new BufferedReader(new 

InputStreamReader(System.in));
            System.out.print("Enter 1st no: ");
            int x=Integer.parseInt(br.readLine());
            System.out.print("Enter 2nd no: ");
            int y=Integer.parseInt(br.readLine());
            System.out.println("\nNumbers Before Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
            //Swapping Method 4
           // x = y-x+(y=x);


            System.out.println("\nNumbers After Swapping:");
            System.out.println("x = "+x);
            System.out.println("y = "+y);
        }
}

While that may work in Java, it's horribly broken in C due to undefined behavior. Further, you've introduced a requirement to check for integer overflow.

For all of the mental gymnastics involved in devising ways to swap without a temporary (though these days everyone just Googles for solutions to look smart), nobody has come up with a general purpose solution that's even comparable to using a temporary, much less superior.

Finally, if you're micro-optimizing to this granularity, you've probably lost perspective as concerns performance and memory usage.

Edited 2 Years Ago by deceptikon

In procedural languages, using a temp is probably best.

I actually can think of one way that does not require any extra variables, works for any datatype and is also very natural. It also doesn't involve any "dirty tricks," or even extra memory over what would be used for not swapping.

It doesn't really fit in the procedural paradime however, so you'll probably want to use a functional language, or at least use a compiler that implements tail call optimization (I think recent versions of gcc does this at -O2). You'll also need to rethink your computation into a functional computation. But if you do then it's natural.

One thing to note though is that this style of programming does not have "variables". So this is the functional analog to the problem. You cannot mutate values (ie, their constant). You instead express each stage of a computation in terms of a function call. So, in order to change the state of anything, you would recurse and change the problem "then" instead of "now".

#include <stdio.h>

void f(const int a, const int b, const int c)
{
    if (c <= 0) return;
    printf("%d %d\n", a, b);
    f(b, a, c-1);
}

int
main(void)
{
    f(5, 6, 5);
}

This of course looks a bit silly in C, but it's normal in other languages.

Edited 2 Years Ago by Hiroshe

I actually can think of one way that does not require any extra variables, works for any datatype and is also very natural.

There are no explicit variables, certainly. However, there's a strong chance that memory will still be allocated to each parameter for each recursive call. So technically you're using more memory than a traditional imperative swap with a temporary.

However, there's a strong chance that memory will still be allocated to each parameter for each recursive call.

Actually, if it implements tail recursion optimization, then you should be ok! I wouldn't always rely on a C compiler being able to do it.

If anyone is wondering what that is, if the final call produces the final answer (proper tail recursion), and the compiler is smart, then it can call the function without moving the stack frame, since no operations need to be done after the result is computed.

There is still a little overhead of calling a function (even if it's optimized with tail recursion), but it's no more then doing anything else functionally. Yes, it's true that the values still need to be placed on the stack, which makes it use a "temporary" variable, but that's completly hidden from the programmer and is no different then the "temporary" variables that are used for all function calls.

Actually, if it implements tail recursion optimization, then you should be ok!

Not really if the goal is to avoid memory use. TRO still introduces hidden variables. Fewer variables, sure, but the purpose of a swap without a temporary is completely defeated.

Keep in mind that the primary goal of these tricks is to avoid the negligible cost of a temporary variable. If your solution doesn't produce this saving, it's a non-solution to the given problem.

If your compairing procedural vs. functional, then yes, you're still pushing the value to the stack. The only advantages are that it's hidden from the programmer, and the space is reclaimed after each call (ie, "temp" won't exist for the duration of the computation, whereas in procedural programming, you'll need to "go out of the way" to return to free the memory used). The cost of that is that not all compilers will support it, and even if it did, it could still introduce some overhead. (keep in mind, not all values are passed to the stack, as described in http://www.x86-64.org/documentation/abi.pdf for the AMD64 architecture. Simular argument for MIPS.) This is the disadvantage.

That's not quite my point though. If your compairing functional to functional, then no new overhead is introduced by swapping variables. In fact, if you use a temp to swap variables, you'll introduce new overhead. So, in a sense of programming in general, there is a way to swap variables without introducing new overhead, just as long as your already using the right paradime.

    #include <stdio.h>
    void main()
    {
    int a,b;
    printf("enter number1:");
    scanf("%d",a);
    printf("enter number2: ");
    scanf("%d",b);
    printf(value of a and b before swapping is a=%d,b=%d"a,b);
    b=a+b-(a=b);
    printf(value of a and b after swapping is a=%d,b=%d"a,b);
    }

Hiii,first you put & line no.6 and 8.
scanf("%d",&a);
scanf("%d",&b);
second erore is line no.9 and 13,so you put the " after the 'printf(' word and put , after 'b=%d"'.
printf("value of a and b before swapping is a=%d,b=%d",a,b);
printf("value of a and b after swapping is a=%d,b=%d",a,b);

You may do it anyway but internally when opcode is generated, it always takes a temp memory for temporary storage. Moreover memory overload problem can always create problem for two large numbers. Swapping two variables using a third variable is hence always better.

This question has already been answered. Start a new discussion instead.