Reputation: 11
int findpow(int n1,int k, int count){ //while calling, k=1, count=0
if(k<n1)
return findpow(n1,k*2,count+1);
if(k==n1)
return count;
if(k>n1)
return --count;
}
This is a function that returns the largest power of two less than n. When I run it in my ubuntu terminal (g++ 4.8.4), it works fine. But when I am running it on www.hackerrank.com, it gives an error(control reaches end of non void function). The problem is, I participate in many contests on this website and I have come across this problem multiple times.
Please tell if you know how I can fix it.
Upvotes: 1
Views: 541
Reputation: 3373
You can use else if
statement like this:
int findpow(int n1,int k, int count){ //while calling, k=1, count=0
if(k<n1)
return findpow(n1,k*2,count+1);
else if(k==n1)
return count;
else // Eliminate compiler errors (warnings)
return --count;
}
or as said @juanchopanza:
int findpow(int n1,int k, int count){ //while calling, k=1, count=0
if(k<n1)
return findpow(n1,k*2,count+1);
if(k==n1)
return count;
// Eliminate compiler errors (warnings)
return --count;
}
It will do the same thing as your code, but will not give a doubt to compiler that can be no return points from function.
Upvotes: 4
Reputation: 880
'control reaches end of non void function' is a warning not an error, it's safe to ignore in this case but if you want to suppress the warning there are multiple ways:
Upvotes: 1