// Swap
// Demonstrates passing references to alter argument variables
#include
<iostream>
using
namespace std;
void
badSwap(int x, int y);
void
goodSwap(int& x, int& y);
int
main()
{
int myScore = 150;
int yourScore = 1000;
cout <<
"Original values\n";
cout <<
"myScore: " << myScore << "\n";
cout <<
"yourScore: " << yourScore << "\n\n";
cout <<
"Calling badSwap()\n";
badSwap(myScore, yourScore);
cout <<
"myScore: " << myScore << "\n";
cout <<
"yourScore: " << yourScore << "\n\n";
cout <<
"Calling goodSwap()\n";
goodSwap(myScore, yourScore);
cout <<
"myScore: " << myScore << "\n";
cout <<
"yourScore: " << yourScore << "\n";
return 0;
}
void
badSwap(int x, int y)
{
int temp = x;
x = y;
y = temp;
}
void
goodSwap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
swap(&grades[num],&grades[num+1]); what it make in a program?
int a,b; a=a+b; b=a-b; a=a-b; that's it simple
swap (int *pa, int *pb) { *pa ^= *pb; *pa ^= *pa; *pa ^= *pb; }
c program was introduced in the year 1972 by Dennis RitchieNo, it was the C language, not the C program.
void swap (int* a, int* b) { if (!a !b) return; // can't swap a pointer to null *a^=*b^=*a^=*b; }
To swap two variables without using a third variable, use exclusive or manipulation... a ^= b; b ^= a; a ^= b;
Ellipses (...) used to emulate indentation... swap(int *a, int *b) { ... int temp; ... temp = *a; ... *a = *b; ... *b = temp; }
swap(&grades[num],&grades[num+1]); what it make in a program?
#include<conio.h> main() { int a,b; scanf("%d%d",&a,&b); printf("Before swapping A= %d B=%d",a,b); swap(a,b); getch(); } void swap(int a,int b) { int c; c=a; a=b; b=c; printf("After swapping A= %d B=%d",a,b); }
a=a^b; b=a^b; a=a^b;
#include using namespace std; void swap(int &a, int &b); int main() { int x=5,y=3; cout
You have to pass the address of the variables.void swap (int *pa, int *pb){...}
int a,b; a=a+b; b=a-b; a=a-b; that's it simple
swap (int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; }
void main() { int a=2,b=5; b=a+b; a=b-a; b=b-a; getch(); }
a page
Consider the following declarations:int x = 0;int y = 1;In order to swap the values, we need to use a temporary variable:int t = x;x = y;y = t;However, it is possible to swap the values without using a third variable:x ^= y ^= x ^= y;