Arrays as Parameters

Jul 3, 2018 at 12:08pm
Hi all
I'm writing a program trying to learn arrays as parameters. i get the syntax error 'undefined reference to swap(int&, int&)'
Here is my code below,

//parameters as refernce
#include <iostream>
using namespace std;

void swap(int& x, int& y);

int main()
{
int a = 100;
int b = 200;

cout << "Value of a before swap: " << a << endl;
cout << "Value of b before swap: " << b << endl;

swap(a,b );
cout << "Value of a after swap: " << a << endl;
cout << "Value of b after swap: " << b << endl;

}

the idea is to have a and b swap values and be printed out.
any help to fix this is appreciated.

Cheers :)
Jul 3, 2018 at 12:12pm
You have to actually write the swap function; you can't just say it exists!

On another note, you might actually run into problems considering you have using namespace std, since there is already a std::swap function that could possibly be indirectly included through <iostream>. Depending on the compiler, you might be able to just get rid of your swap declaration and it would work. (Don't do this)
Last edited on Jul 3, 2018 at 12:15pm
Jul 3, 2018 at 12:13pm
Firstly, you aren't using arrays, so the title of the thread is rather unrepresentative of its content.

Secondly, you haven't written any code for your function swap ... so the compiler dutifully tells you so!

You have written a function prototype:
void swap(int& x, int& y);
so the program knows what types of arguments it would like to use. However, you haven't actually written the function itself.

It will look something like this:
1
2
3
4
void swap(int& x, int& y)
{
   // The code you are going to write goes here.
}


PLEASE USE CODE TAGS WHEN POSTING.
Last edited on Jul 3, 2018 at 12:18pm
Topic archived. No new replies allowed.