Exchange two numbers


I was just thinking of writing a C++ function for exchanging two numbers, with the difference that it should be able to clear all kinds of test cases. Here is the program.

 

#include<iostream>

using namespace std;

typedef unsigned int uint;

void xchange(uint *a1,uint *a2){
 if(a1==a2) return;
 if(a1==NULL || a2==NULL) return;
 uint tem;
 tem=*a1;
 *a1=*a2;
 *a2=tem;
 }

int main(){
 uint a1,a2;
 a1=22,a2=23;
 cout<<a1<<" "<<a2<<"\n";
 xchange(&a1,&a2);
 cout<<a1<<" "<<a2<<"\n";
 system("pause");
 return 0;
 }

The function here checks first for any of the null addresses passed and moreover checks if the two numbers are same. If the numbers are same, we do not need to exchange the two numbers, thus saving us some valuable steps.

You might think that saving such pity steps won’t do any good, but think of this function. How many times do you think we may call this function in a program? Exchanging values is a very common task, so if we call this function even if only 4 times in a program and run that program 10 times a day on an average, then in an year, we are saving to call those 3 steps, 14600 times a year approx.

Advertisements
Explore posts in the same categories: C++

Tags: , , ,

You can comment below, or link to this permanent URL from your own site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: