Question:

Is there any other method to swap the values of 2 variables?

by  |  earlier

0 LIKES UnLike

I have the following program where i swap the values of 2 variables by using pointers. Can i swap them without using the variable "temp"?

Can i just use pointers to swap the values of 2 variables?.Please explain and comment.

#include <iostream.h>

main()

{

int i, *ptr_i;

int j, *ptr_j;

int temp;

i=7;

j=11;

cout<<"Value of i: "<<i<<"\n";

cout<<"Value of j: "<<j<<"\n\n";

ptr_i = &i;

ptr_j = &j;

temp = *ptr_i;

i = *ptr_j;

j = temp;

cout<<"Value of i: "<<i<<"\n";

cout<<"Value of j: "<<j<<endl;

system("pause");

}

 Tags:

   Report

2 ANSWERS


  1. This is how you swap two variables without an intermediate:

    int a;

    int b;

    a^=b^=a^=b;

    Similarly, you can swap values given just the pointers:

    int* pa = &amp;a;

    int* pb = &amp;b;

    *pa^=*pb^=*pa^=*pb;

    However, if pa and pb point to the same location, then *pa is zeroed, and *pb does not change in value - the swap fails.

    This swapping procedure is called the triple-XOR swap and should be avoided.


  2. int a,b;

    a=a+b;

    b=a-b;

    a=a-b;

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.