return by reference

A

asit

Please fix the bugs ..???


#include <iostream>
//#include <cstdio>

using namespace std;

int& swap(int a, int b)
{
return (a>b)?a:b;
}
int main()
{
int a,b;
cout<<"Enter a and b : ";
cin>>a>>b;
max(a,b)=-1;
cout<<a<<"\t"<<b<<endl;
//getchar();
return 0;
}
 
D

diligent.snail

Please fix the bugs ..???

#include <iostream>
//#include <cstdio>

using namespace std;

int& swap(int a, int b)
{
return (a>b)?a:b;}

'a', 'b' are local to 'swap'. Never return a reference to local non-
static function variables (dangling references). You can do:

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


int main()
{
int a,b;
cout<<"Enter a and b : ";
cin>>a>>b;
max(a,b)=-1;

'max' returns a constant reference, to which you can not assign.
cout<<a<<"\t"<<b<<endl;
//getchar();
return 0;

}


Regards.
 
J

Jensen Somers

asit said:
Please fix the bugs ..???


#include <iostream>
//#include <cstdio>

using namespace std;

int& swap(int a, int b)
{
return (a>b)?a:b;
}
int main()
{
int a,b;
cout<<"Enter a and b : ";
cin>>a>>b;
max(a,b)=-1;
cout<<a<<"\t"<<b<<endl;
//getchar();
return 0;
}

There are a lot of things wrong with this code. This group is not going
to do your homework, so take your textbook and review the C++ lessons.

Alternatively, you can use Google to find a C++ swap integers function
and see why your code is wrong.

Pointer: the error is located near the swap() call.

- Jensen
 
D

Daniel T.

asit said:
Please fix the bugs ..???

We can't fix the bugs unless we know what the correct behavior is
supposed to be. We only point them out.
#include <iostream>
//#include <cstdio>

using namespace std;

int& swap(int a, int b)
{
return (a>b)?a:b;
}

The above would cause a bug if it was being used, but since it isn't...
Don't return a reference to a function-scope variable.
int main()
{
int a,b;
cout<<"Enter a and b : ";
cin>>a>>b;
max(a,b)=-1;

illegal assignment to constant.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,968
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top