Thursday, April 28, 2022

[FIXED] Why does the function foo cannot return properly?

Issue

I am trying to write a recursive function in C programming but the compiler keeps give me warning: control may reach end of non-void function. I don't know where do i get wrong.

int foo(int* ptr){
  int flag = 0;
  --(*ptr);
  if((*ptr)!=0) flag = 1;
  if(flag == 0) return 1;
  else foo(ptr);
}

int main()
{
  int count=10;
  int* ptr = &count;

  int n = foo(ptr);
  printf("%d", n);

  return 0;
}

Thank you.


Solution

in your else statement in function foo you are not returning anything.

it should be like this:

int foo(int* ptr) {
    int flag = 0;
    --(*ptr);
    if ((*ptr) != 0) 
        flag = 1;
    if (flag == 0) 
        return 1;
    else return foo(ptr);
}


Answered By - hanie
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.