简体   繁体   中英

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

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".

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 correct 1 overload is called.


1 For some definition of correct, in this case

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM