what is the difference between
int &a=b;
int *a=b;
if we replace (int a,int b) in gcd function by (int &a,int &b)
why it gives compile error
What is the difference between int &a=b; int *a=b; if we replace (int a,int b) in gcd function by (int &a,int &b) why it gives compile error
int &a=b;
here both a and b point to same location, a is just a different name to b.
int *a=b ;
Here, a is a pointer of type int , and a points to the address b (not to the location b, suppose b=10, then a will point to address 10)
to make pointer for b
int *a=&b;
now taking
func (int a,int b)
here parameters are passes by value, that is any changes made in the function will not reflect back to original calling function.
func (int &a, int &b)
is passing by reference, any changes made to parameter will be reflected in calling function.
I do not your gcd functions definition but if you are using recursion then one of the number might have become zero in calls, and then you would be using that number to divide or take modulo so error.
If this resolves your doubt mark it as resolved.
i am using this as my gcd function
int gcd(int &a,int &b)
{
return (b==0)?a:gcd(b,a%b);
}
int main() {
int a,b;
a=5;b=4;
cout<<gcd(a,b);
return 0;
}
@tusharkhandelwal315 that is because a%b is constant, you cannot pass constants as parameter when using pass by value.
Use if else and store a%b in some variable and pass that variable (take care you that b is not zero)
int gcd(int &a,int &b)
{
if(b==0)
return a;
int c=a%b;
return gcd(b,c);
}
Though doing this is not advised pass parameters by value or by pointer only when you want the change to be reflected back in calling functions(many times this is not the case)
If this resolves your doubt mark it as resolved.