Amit Mittal
Amit Mittal

Reputation: 11

I am trying to swap two values by pass by reference there is no error occur but the compiler throw some message

I am trying to swap two numbers using pass by reference but it is not executing.

#include<iostream>
using namespace std;
void swap(int,int);

    int main(){
        int x,y;
        cin>>x>>y;
        swap(x,y);
        cout<<"x= "<<x<<"y= "<<y;
        return 0;
    }

    void swap(int &x,int &y){
        int temp;
        x=temp;
        x=y;
        y=temp;
        cout<<"x= "<<x<<"y= "<<y;
    }

Compiler shows this error:

C:\Users\amitm\AppData\Local\Temp\ccu8znRO.o:swap_reference.cpp:(.text+0x49): undefined reference to `swap(int, int)' collect2.exe: error: ld returned 1 exit status

Upvotes: 1

Views: 414

Answers (1)

t.niese
t.niese

Reputation: 40842

The signature of the declaration void swap(int,int) is not equal to the one of the definition void swap(int &x,int &y).

At the time when swap is called only the declaration void swap(int,int) is known and used, but for that declaration, there is no definition anywhere, and that's what the linker complains about:

undefined reference to `swap(int, int)' collect2.exe: error: ld returned 1 exit status

(the ld in an error message tells you that it is a linker error, and linker errors indicate that you have mismatching definitions and declarations in your own code, or that you are missing a library)

You have to change the declaration to match the definition void swap(int&,int&);

Upvotes: 2

Related Questions