Passing arguments by pointer question

Hi I'm currently learning C++ and I got to an exercise that asked to create a function that swaps two ints passed in by pointer. Here is that snippet of the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void swap(int *num1, int *num2)
{
    int tmp = *num2;
    *num2 = *num1;
    *num1 = tmp;
}

int main()
{
    cout << "Enter in two numbers to swap around: ";
    int num1, num2;
    cin >> num1 >> num2;
    cout << "Before swap num1 = " << num1 << '\n'
         << "Before swap num2 = " << num2 << endl;
    swap(&num1, &num2);
    cout << "After swap num1 = " << num1 << '\n'
         << "After swap num2 = " << num2 << endl;
    return 0;
}


Everything works just fine, but the first time I compiled it I noticed I forgot the address of operators and called swap like this:

swap(num1, num2);

and it compiled and worked. I don't understand how the version without the ampersands can work when the function parameters are expecting a pointer to int but is allowing me to pass plain int values as arguments?
Last edited on
> I don't understand how the version without the ampersands can work
> when the function parameters are expecting a pointer to int

It does not work. http://coliru.stacked-crooked.com/a/cce42745ba4ef2ef
closed account (ivDwAqkS)
Wallboy maybe it was because you didnt use the asterics pointer the first time you compiled in your function. thats why it worked without the ampersands, however you will see the diferience with problems or algorithm much bigger why you have to use pointers to completely manage the value of the variable
Last edited on
Ok I think I might have an include including some other swap function or something. I just renamed my function and now it fails to compile with the error I would have expected. Would this be possible?
Yes, you may be right. The function in question would like be:
http://www.cplusplus.com/reference/utility/swap/
I'm using code:blocks btw, and yeah when I hightlight over my swap function definition it shows a bunch of other possible swap functions and also highlights the function name in green. When I made my own really unique function name there is no highlighting on it.

So I guess I was just calling another swap function that just happened to work lol. Thanks guys.
closed account (ivDwAqkS)
yes, Wallboy it depends on what library you are using, try to use other name for you own swap function if you are not using pointers.
Topic archived. No new replies allowed.