fate_blast
fate_blast

Reputation: 11

control reaches end of non-void function (only on particular IDEs)

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

Answers (2)

Mykola
Mykola

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

1stCLord
1stCLord

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:

  • put a return after the last condition
  • as Mykola suggested restructure the conditions to be explicit
  • set the -Wno-return-type flag

Upvotes: 1

Related Questions