2

I understand without &, the values are passed by value. Consider the following code snippet:

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


int main()
{
    int a=10, b=20;
    swap(a,b);
    cout << a << " " << b << endl;
    return 0;
}

The output will be : 10 20

However if the swap function is placed after the main function and there is no function declaration before the main. That is...


int main()
{
    int a=10, b=20;
    swap(a,b);
    cout << a << " " << b << endl;
    return 0;
}

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

In this case the output is going to be : 20 10.

Shouldn't the o/p also be 10 20 in the second case. Can someone please help me to understand as to ow is pass by reference happening here?

0 Answers0