Emi Anyakpor
Emi Anyakpor

Reputation: 13

How to rewrite this function into a pointer in c++?

void swap(int &a, int &b)
{
      int temp = a;
      a = b;
      b = temp;
}

In my code all I did was add asteriks before the variables a, b in both the argument and in the body of the code. My teacher said it was wrong so now I don't get it.

Upvotes: 0

Views: 223

Answers (1)

GreatAndPowerfulOz
GreatAndPowerfulOz

Reputation: 1775

void swap(int *a, int *b)
{
      int temp = *a;
      *a = *b;
      *b = temp;
}

the way you would call your original would be:

int one = 1;
int two = 2;
swap(one, two); // references

the modified function like

swap(&one, &two); // pointers

Upvotes: 4

Related Questions