Akshat
Akshat

Reputation: 43

Passing value to pointer parameters in C++

In the following code, why does the swap function work in two ways, by passing values as swap(x,y) and swap(&x, &y).

int main(){

   int x, y;

   cout << "Enter the values of x and y: ";
   cin >> x >> y;

   swap(x, y);

   cout << "\nSwapped values are, x: " << x << " & y: " << y <<"\n";

   return 0;

}

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

   int s;
   s = *a;
   *a = *b;
   *b = s;

}

Upvotes: 4

Views: 192

Answers (3)

apple apple
apple apple

Reputation: 10591

you call std::swap when you write swap(x, y);


In your example, even if you write the swap(&x, &y); you will only get compile error unless you declare void swap(int*,int*); before main.

And std::swap can not help on this because it cannot convert rvalue int* to int*&. (even if it can do this, it will not swap the value of x and y)


Upvotes: 7

legends2k
legends2k

Reputation: 32904

Here's the explanation to the other answer, on why std::swap is called:

When you swap(x, y), the compiler tries to look for a swap overload to call. Assuming you had written using std::swap; or using namespace std;, the namespaces the compiler is allowed to look would be global and std.

The prototype void swap(int, int) is expected but the compiler is open to options -- functions with same name, same count of parameters but different parameter types that need coercion are OK too -- when looking for a viable overload; after enumerating them, it would choose the closest match.

The one that you've implemented, in the global namespace, is of type

void swap(int*, int*);

but the one given by the standard library header <utility> is a function template

namespace std {
    template <typename T>
    void swap(T&, T&);
}

This overload becomes void swap(int&, int&) since T = int. Now this is an identity match (no type coercion required) and hence wins the overload resolution.

Had you not written using std::swap; or using namespace std;, then the only possible overload available to the compiler would have been yours, to which you'd have gotten an error saying the argument types mismatch. Fixing it would be fixing the calling code to pass int* (address of those variables are of type pointer to int) and not int:

swap(&x, &y);

Upvotes: 7

Vrana
Vrana

Reputation: 31

When you call the version swap(x,y) it actually calls the standad library function template "template void swap (T& a, T& b)" , declared in "algorithm" header file.

Upvotes: 2

Related Questions