#Trouble understanding passing by pointer

17 messages · Page 1 of 1 (latest)

fathom wedge
#

So I have this

#include <iostream> 
using namespace std;

void swap(int *x, int *y) {
    int temp = *x;
    *x = *y; 
    *y = temp; 
}

int main() {
    int a = 4;
    int b = 3;
    swap(a, b);
    cout << a << endl << b;
}

What I don't understand is why this works, in all the examples of this I see online they use references ie &a and &b, which makes sense but this somehow works too, why?

pliant rampartBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

torn ember
#

hi, i) this is C++ not C, ii) this won't work, you need to pass &a and &b instead of themselves

fathom wedge
#

but it does work

torn ember
#

but it can be answered the same way for C or C++: this uses pointers

#

no that won't work

tight cargoBOT
#
Program Output
3
4
torn ember
#

oh my

#

i see

#

you are calling the Standard library's swap, not yours

#

because of using namespace std;

#

there is std::swap as well

fathom wedge
#

ur right

#

lol

torn ember
#

and your custom swaps parameters are pointers, you got integers, so yours won't be called due to mismatch

fathom wedge
#

i did get an error, thankfully