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

(Last Updated On: February 25, 2019)

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