swap (int *a, int *b) {
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int c = 13;
int d = 27;
swap (&c, &d); /*c is now 27 and d is now 13 */
Note: there is no call-by-reference in C. In C++:
void swap (int &a, int &b)
{
. int tmp;
. tmp = a;
. a = b;
. b = tmp;
}
Chat with our AI personalities
#include <iostream>
using namespace std;
void swap(int& x, int& y)
{
x ^= y ^= x ^= y; // Swap values without using temporary variable.
}
int main()
{
int a=1, b=2;
cout<<"Before:\t";
cout<<"a="<<a<<"\tb="<<b<<endl;
swap(a,b);
cout<<"After:\t";
cout<<"a="<<a<<"\tb="<<b<<endl;
return( 0 );
}
The only way to swap two values using call by value semantics is to pass pointer variables by value. A pointer is a variable that stores an address. Passing a pointer by value copies the address, the value of the pointer, not the pointer itself. By passing the addresses of the two values to be swapped, you are effectively passing those values by reference. Both C and C++ use pass by value semantics by default, however C++ also has a reference data type to support native pass by reference semantics. By contrast, Java uses pass by reference semantics by default. In C, to swap two variables using pass by value: void swap (int* p, int* q) { int t = *p; *p = *q; *q = t; } In C++, to swap two variables using pass by reference: void swap (int& p, int& q) { std::swap (p, q); } Note that C++ is more efficient because std::swap uses move semantics; there is no temporary variable required to move variables. With copy semantics, a temporary is required. However, with primitive data types, there is a way to swap values without using a temporary, using a chain of exclusive-or assignments: void swap (int* p, int* q) { *p^=*q^=*p^=*q; }
#include<iostream> using namespace std; void swap(int &i, int &j) { int temp = i; i = j; j = temp; } int main() { int i,j; cin>>i>>j; cout << i << j << endl; swap(i,j); cout << i << j; return 0; }
#include<iostream> void swap(int* x, int* x){ (*x)^=(*y)^=(*x)^=(*y); } int main() { int a, b; a=10; b=20; std::cout<<"Before swap: a="<<a<<", b="<<b<<std::endl; swap(&a,&b); std::cout<<"After swap: a="<<a<<", b="<<b<<std::endl; return(0); }
Use list assignment i.e. for two variables $a, $b: ($a,$b) = ($b,$a)
Call By Value, the standard way of doing things in C and C++, is where a copy of an object is placed in the parameter stack. The called function can access and manipulate that copy at will, but it cannot change the original copy because it has no way of knowing where that original copy is located. Call By Reference, on the other hand, is where the address of an object is placed in the parameter stack. Using extra syntax, the * or the ->, the called function can access and manipulate the original copy at will.