Baqar Hussain Baqar Hussain - 16 days ago 5
C Question

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

Answer

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