C++ program to swap two numbers using pointers and references

C++ program to swap two numbers using pointers and references and functions. Swapping two number using pointers concept is applicable to both C and C++. But, swapping two numbers by reference is applicable to C++ only, as C language does not support references. Recommended to read about pointer and reference in C++ programming.

Focus point : There is no concept of reference in C but in C++ only.

Interview Question: Write swap function to swap two numbers using pointers in C++ and also write code to swap two numbers or variables using reference. You don’t have to swap in main() function , but, write a function to swap using pointer and another function to swap using reference in C++ and call them from main() program.

Note: The swap function using pointers is asked in an interview to know the very basic pointer concepts. In this method programmer can make the mistake at line int temp = *a; and the general mistake is “int *temp = *a;” instead of “int temp = *a;”.

In below C++ source code example, swap() function is implemented using both pointers and reference to swap two numbers or variables

C++ program to swap two numbers using pointers and references

// swap function using pointer
void swapUsingPointer(int *a, int *b){
	int temp = *a;
	*a = *b;
	*b = temp;
}

//swap function using reference
void swapusingReference(int &a, int &b){
	int temp = a;
	a = b;
	b = temp;
}

int main(){	

	int a = 2;
	int b = 5;

	printf("Before Swap : a = %d, b = %d\n",a,b);

	//swap variables using pointer
	swapUsingPointer(&a,&b);//pass address of variables
	printf("After Swap : a = %d, b = %d\n",a,b);

	//swap using reference.
	swapusingReference(a,b);// just pass the values of variables
	printf("After again Swap : a = %d, b = %d\n",a,b);	

	return 0;
}

Related Posts