Stroustrup 5.9, exercise 4 (page 105)
this programme compiles but runs into some strange results, a semantic-
BUG is there. i even put some "std::cout" to know what is wrong but it
does something that i did NOT order it to do:
--------------- PROGRAMME -------------------
/* Stroustrup, 5.9 exercise 4
STATEMENT:
write a programme that swaps 2 integers. solve it
using 1st with pointers and then references.
METHOD:
1.) asks the user to input 2 integers
2.) swaps the value using pointers,
prints 2 statements to show what it is doing
3.) prints the SWAPPED values
4.) swaps the vale sagain using References
5.) so after swapping 2 times we get the original input values.
*/
#include<iostream>
void swap_p(int* x, int* y);
void swap_r(int& x, int& y);
int main()
{
using std::cout;
using std::cin;
using std::endl;
int i;
int j;
cout << "Enter 1st integer: ";
cin >> i;
cout << "enter 2nd integer: ";
cin >> j;
cout << "i = " << i << '\t'
<< "j = " << j << endl;
int* pi = &i;
int* pj = &j;
swap_p(pi, pj);
cout << "\nvalues swapped using Poiners\n"
<< "i = " << i << '\t'
<< "j = " << j << endl;
swap_r(i, j);
cout << "\nswappe dusing Refrences\n"
<< "i = " << i << '\t'
<< "j = " << j << endl;
return 0;
}
void swap_p(int* x, int* y)
{
int temp_val = *x;
x = y;
std::cout << "------------------------------\n";
std::cout << "x = " << *x << "\ty = " << *y <<'\n';
*y = temp_val;
std::cout << "x = " << *x << "\ty = " << *y <<'\n';
std::cout << "------------------------------\n";
}
void swap_r(int& x, int& y)
{
int temp_val = x;
x = y;
y = temp_val;
}
-------------- OUTPUT ------------------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra 5.9_ex-04.cpp
[arch@voodo tc++pl]$ ./a.out
Enter 1st integer: 3
enter 2nd integer: -2
i = 3 j = -2
------------------------------
x = -2 y = -2
x = 3 y = 3
------------------------------
values swapped using Poiners
i = 3 j = 3
swappe dusing Refrences
i = 3 j = 3
[arch@voodo tc++pl]$
------------------------------
x = -2 y = -2
x = 3 y = 3
------------------------------
1st line is fine but why does it change value of "x" in 2nd line.i did
not do anything to "x"
?