Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}
like image 350
Akshat Avatar asked Dec 04 '22 23:12

Akshat


2 Answers

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)


like image 20
apple apple Avatar answered Dec 08 '22 00:12

apple apple


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);
like image 141
legends2k Avatar answered Dec 07 '22 23:12

legends2k