Thursday, 20 July 2017

Confusion about pointers and references in C++



I have a bunch of code like this:



#include 
using namespace std;

void swap(int *a, int *b) {
int temp = *a;
*a = *b;

*b = temp;
}

int main() {

int a;
int b;
a = 7;
b = 5;
swap(a, b);

cout << a << b;

return 0;
}


This code does the swapping process as what I exactly wanted to swap 2 numbers



But when I want two numbers from the user as follows;




int a;
int b;
cin >> a;
cin >> b;
swap(a, b);
cout << a << b;


The compiler gives me an error about integer to *integer error which is as expected. Why does the first code do the right swapping although I didn't use the method with & operator?


Answer




In the first example, std::swap is called, because of your using namespace std.
The second example is exactly the same as the first one, so you might have no using.



Anyway, if you rename your function to my_swap or something like that (and change every occurence), then the first code shouldn't work, as expected. Or, remove the using namespace std and call std::cin and std::cout explicitly. I would recommend the second option.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...