Home > OS >  c program Warning the control reaches the end of non-void function
c program Warning the control reaches the end of non-void function

Time:02-10

so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error

#include <iostream>
//int sum = 1;

int powerOfNumber(int n, int p) {
    if (n != 0) {
        p--; 
        return powerOfNumber(n , p) * n;
    }
    if (n == 0) {
        return 1;
    }
}


int main()
{
    std::cout <<powerOfNumber(5, 2);
   

    return 0;
    
}

CodePudding user response:

Your stop condition must be in terms of p, not n, because that's the variable you are substracting the value, either way you could substract the value of n

CodePudding user response:

#include <iostream>

using namespace std; 

int powerOfNumber(int n, int p) {
    if(p==0)
        return 1;
    else 
        return (n*powerOfNumber(n,p-1));     
}


int main()
{
    std::cout <<powerOfNumber(5, 2);

    return 0;
}

Your powerOfNumber function never terminates because n is always 5.

CodePudding user response:

You have a bug that the condition needed to be

    if (p != 0) {
    ...
    }
    if ( p == 0)
        return 0;

rather than if (n != 0) { ... } if ( n == 0) ....

But you might still get the same warning though if the compiler couldn't deduce that there'll be always be a return.

You could simply rewrite it to:

int powerOfNumber(int n, int p) {
   if (p != 0) {
       p--; 
       return powerOfNumber(n , p) * n;
   }

   return 1;
}

so that there's always a return statement unconditionally.

P.S.: Be aware that if you are using a large input for either n or p, you might run to integer overflow.

  •  Tags:  
  • c
  • Related