swap function

Hello, i'm new to the site so sorry if i mess something up.

my program doesn't seem to work. the final cout in the main doesn't show that the numbers switched. it seems to call the function just fine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

void swap(int, int);

int main()
{
    int i=0, j=1;

    cout<<i<<" "<<j<<"\n";

    swap(i, j);

    cout<<i<<" "<<j;

	cout<<"\n\n";
	return 0;
}

void swap (int a, int b)
{
    int t;
    t=a;
    cout<<t<<endl;
    a=b;
    cout<<a<<endl;
    b=t;
    cout<<b<<endl;
    return;
}

output is:
0 1
0
1
0
0 1

but it should be:
0 1
0
1
0
1 0
Last edited on
If you want to actually alter a and b pass in references instead:

void swap(int &a, int &b);

Right now you're passing in a value that doesn't remain after the call to swap()
Topic archived. No new replies allowed.