The below function is showing an error : C:\Users\my pc\Documents\C++\Slide7Pointer.cpp [Error] invalid conversion from 'int' to 'int*' [-fpermissive]
Please tell where is the mistake and how to correct it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
usingnamespace std;
int main()
{
int m=44, n=22;
int max(int &, int &);
int *q=max(m,n);
cout<<"m="<<m<<"\t"<<"n="<<n<<" *q"<<*q<<endl;
m=55;
cout<<"m="<<m<<"\t"<<"n="<<n<<" max(m,n)="<<max(m,n)<<endl;
}
int &max(int &m,int &n)
{
return(m>n?m:n);
}
int & is a reference to an int, not a pointer to an int. On line 8, you are trying to assign the result of max() to a pointer. Instead, make it a reference, like what your actual function returns.
On line 7, your prototype does not match your function definition on line 14. Your prototype should declare the return type as an int&, not an int.
Also, don't be afraid of whitespace... IMO it really helps readability.
#include<iostream>
usingnamespace std;
int main()
{
int& max(int &, int &); // prototype
int m = 44;
int n = 22;
int& q = max(m,n);
cout << "m = " << m << "\t" << "n = " << n << " q = " << q << endl;
m = 55; // q is a reference to m now
cout << "m = " << m << "\t" << "n = " << n <<" max(m,n) = " << q << endl;
// q is updated because it's a refeernce to m
}
int& max(int &m, int &n)
{
return (m > n ? m : n);
}
#include<iostream>
usingnamespace std;
int main()
{
int* max(int &, int &); // prototype
int m = 44;
int n = 22;
int *q = max(m,n);
cout<<"m="<<m<<"\t"<<"n="<<n<<" *q"<<*q<<endl;
m=55;
cout<<"m="<<m<<"\t"<<"n="<<n<<" max(m,n)="<<max(m,n)<<endl;
}
int* max(int &m, int &n)
{
return (m > n ? m : n);
}