Swapping an integer value C++ program sample using function which pass argument by value
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Swapping an integer value in C++ programming
To show: How to swap an integer value in C++ programming using user defined function
// the C++ function - demonstrates passing argument (by value) to a function
#include <iostream>
// function prototype
void swap(int x, int y);
int main(void)
{
int x = 5, y = 10;
std::cout<<"In main. Before swap, x: "<<x<<" y: "<<y<<"\n";
std::cout<<"\nThen calling function swap(x, y)...\n";
// function call
swap(x, y);
std::cout<<"\n...back to main. After swap, x: "<<x<<" y: "<<y<<"\n";
return 0;
}
void swap(int x, int y)
{
int temp;
std::cout<<"\nIn swap function, confirm before swapping, x: "<<x<<" y: "<< y << "\n";
temp = x;
x = y;
y = temp;
std::cout<<"In swap function. After swapping, x: "<<x<<" y: "<<y<<"\n";
}
Output example:
In main. Before swap, x: 5 y: 10
Then calling function swap(x, y)...
In swap function, confirm before swapping, x: 5 y: 10
In swap function. After swapping, x: 10 y: 5
...back to main. After swap, x: 5 y: 10
Press any key to continue . . .