A Pointer question.

suppose i want to swap two pointers of two variables

this code which i think the correct one, does not swap the numbers(orders does not change):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
using namespace std;

void swap(int*, int*);
void swap(int* a, int* b){
  
  int* tmp{nullptr};

  tmp = a;
  a = b;
  b = tmp;
}
int main()
{
  int num1{23};
  int num2{99};
  
  int* num1Ptr{nullptr};
  int* num2Ptr{nullptr};

  num1Ptr = &num1;
  num2Ptr = &num2;
  
  cout << *num1Ptr << " " << *num2Ptr << "\n";
  swap(num1Ptr, num2Ptr);
  cout << *num1Ptr << " " << *num2Ptr << "\n";
  
  return 0;
}


but this one works fine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>

using namespace std;

void swap(int*, int*);
void swap(int* a, int* b){
  
  int* tmp{nullptr};

  tmp = a;
  a = b;
  b = tmp;
}

int main()
{
  int num1{23};
  int num2{99};

    
  cout << num1 << " " << num2 << "\n";
  
  swap(num1, num2);//<==THE ARGUMENTS ARE NOT POINTERS BUT NO COMPILER ERROR EVEN WE DEFINED THE FUNCTION ARGUMENTS AS TWO POINTERS.

  cout << num1 << " " << num2 << "\n";
  
  return 0;
}


Why does not work the first code?
Why no errors in the second code and works fine?
For the first one without using...:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
//using namespace std;

void swap(int* a, int* b) {
	const int tmp {*a};
	*a = *b;
	*b = tmp;
}

int main()
{
	int num1 {23};
	int num2 {99};

	int* num1Ptr {&num1};
	int* num2Ptr {&num2};

	std::cout << *num1Ptr << " " << *num2Ptr << "\n";

	swap(num1Ptr, num2Ptr);

	std::cout << *num1Ptr << " " << *num2Ptr << "\n";
}


For the second one without using...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>

//using namespace std;

void swap(int* a, int* b) {

	int* tmp {nullptr};

	tmp = a;
	a = b;
	b = tmp;
}

int main()
{
	int num1 {23};
	int num2 {99};

	std::cout << num1 << " " << num2 << "\n";

	swap(num1, num2);

	std::cout << num1 << " " << num2 << "\n";

	return 0;
}


You get a compiler error "void swap(int *,int *)': cannot convert argument 1 from 'int' to 'int *'"

The reason it worked before is that there is a swap() as part of STL and with the using statement, the STL one was used instead of the one in the code. That's why it compiled OK and ran. Removing the using statement meant that the compiler no longer considered the STL swap() as it's not in the global namespace.

This is the reason that having using... in a program is a Bad Idea.
Last edited on
Why does not work the first code?
You need to pass the pointer by reference otherwise only copies are used:

void swap(int*&, int*&); // Note: &


Why no errors in the second code and works fine?
Because not your swap(...) but a swap(...) from the std namespace is used.
Topic archived. No new replies allowed.