Reputation: 548
#include <iostream>
void swap(int &pi, int &pj){
std::cout << "In function swap: " << &pi << " " << &pj << "\n";
int temp = pi;
pi = pj;
pj = temp;
}
int main(){
int i = 10, j = 20;
int *pi = &i, *pj = &j;
swap(pi, pj);
std::cout << *pi << " " << *pj;
return 0;
}
The above program does not give any compilation error. (Though to swap function in not POINTER TO REFERENCE type) and gives the proper output. But whatever i am trying to print inside "swap" function is not printed to console. Can anybody explain me why?
Upvotes: 1
Views: 2148
Reputation: 1
If you can compile your program, you don't show us all of your code. This code snippet you posted doesn't compile, because you're trying to pass to objects of type int* to your function swapm which expects a reference to an int.
If your code compiles, I suspect you to include a 'using namespace std;' anywhere in your original code.
Upvotes: 0
Reputation: 1615
you're trying to get the address of a pointer that you're passing by reference... I don't think you quite understand what you're doing. the pass by reference feature in C++ allows you to pass a reference, so you don't need a pointer. Your code should look like this.
#include <iostream>
void swap(int &i, int &j){
std::cout << "In function swap: " << i << " " << j << "\n";
int temp = i;
i = j;
j = temp;
}
int main(){
int i = 10, j = 20;
swap(i, j);
std::cout << i << " " << j;
return 0;
}
Upvotes: -1
Reputation: 213059
Looks like you're probably using std::swap
to swap two pointers instead of calling your own swap routine. I suspect you have a using namespace std;
somewhere that you are not showing us ? Try changing the name of your swap routine to e.g. my_swap
and then see if calling my_swap
works (it should fail with a compilation error).
Upvotes: 9