Baqar Hussain
Baqar Hussain

Reputation: 1

Swap Function - pointers - confusion

Notice in the code that I am not using pointers, but I had concepts that if I would use this function, the value would return back to normal when the code block is finished.

But the code is compiling with the answer which I would get with pointers actually.

I need help as I am confused if I have foul concept related to pointers.

void swap(int i, int j) {
    int temp = i;
    i = j;
    j = temp;
}

int main() {
    int a = 110;
    int b = 786;
    cout << "Before swapping the value" << endl;
    cout << "'a' stores the value : " << a << endl;
    cout << "'b' stores the value : " << b << endl;
    swap(a,b);
    cout << "\nAfter swapping the value" << endl;
    cout << "'a' stores the value : " << a << endl;
    cout << "'b' stores the value : " << b << endl;
    swap(a, b);
    cout << "\nAnd back again swapping the value" << endl;
    cout << "'a' stores the value : " << a << endl;
    cout << "'b' stores the value : " << b << endl;

    return 0;
}

I am getting results without using pointers - is this IDE problem

Upvotes: 0

Views: 122

Answers (3)

It seems the iostream header you included also includes the utility header; and you get a definition of std::swap pulled into your program.

Since you (don't show it, but probably) have using namesapce std; in your code, the overload set for swap contains both overloads. And by the rules of overload resolution, the correct1 overload is called.


1 For some definition of correct, in this case

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117876

Your swap function will not swap the values in the scope of main, because i and j are function local variables. To get the behavior you expect, you should pass by reference.

void swap(int& i, int& j) {
    int temp = i;
    i = j;
    j = temp;
}

Your code will not actually swap the values.

Guess:
I think that you are using namespace std; and from one of your #include from the standard library you are colliding with std::swap. I think the std:: version of the function is being called in your case, that is the only reason your code appears to "work".

Upvotes: 6

Vada Poch&#233;
Vada Poch&#233;

Reputation: 780

If you want to use pointers to swap, you should pass by pointers:

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

Passing by reference is another option, as another user has pointed out.

PS: Your query has nothing to do with function-pointers, so I'll be removing the function-pointer tag from your query.

Upvotes: 0

Related Questions