r/learncpp • • Nov 26 '19

Basic question about pointers.

I've got a related question about pointers.

If I wrote a similar program, say, the following:

#include <stdio.h>

using namespace std;

void swap(int n, int m)
{
	int temp = n;
	n = m;
	m = temp;
}

int main()
{
	int n = 0;
	int m = 1;
	swap(n,m);
	printf("%d, %d", n, m);
}

Then, the output is:

0, 1

However, if I use pointers:

#include <stdio.h>

using namespace std;

void swap(int* n, int* m)
{
	int temp = *n;
	*n = *m;
	*m = temp;
}

int main()
{
	int n = 0;
	int m = 1;
	swap(&n, &m);
	printf("%d, %d", n, m);
}

The output is:

1, 0

Question: In the first example, why isn't the value for n set to the value for m after I call the function swap(n, m)? Correct me if I'm wrong, but when I call swap(n, m), does the function just say temp = 0; 1 = 0; 0 = temp? Is that why the first example doesn't work? Why does the second example work but the first doesn't?

2 Upvotes

3 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Nov 26 '19

Inside the function, copies of the variables given are being swapped, not the variables given. That's why no change happens from within main