0
void *returnMin(PQueue q){
  if (q.list == NULL){
    printf("List is empty.\n");
  } else if (q.list->head == NULL){
    printf("List is empty.\n");
  } else {
    return q.list->head;
  }
}

Currently working on Priority queues, everything seems to be working except when I try to return the min and max priorities, I get the error. We are using 3 structs, the 3rd one being a struct pointer.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
dillam
  • 11
  • 4
  • 2
    Only one of those conditional code blocks returns a value for the function. The others do not, and there is no `return XXX;` at the end of the function. – Weather Vane Apr 16 '20 at 17:19
  • 1
    you need to return something in all case, considering you visibly return a pointer you can return NULL in the two fist cases. WIthout a return the behavior will be undefined. – bruno Apr 16 '20 at 17:20
  • Does this answer your question? [Error: control may reach end of non-void function in C](https://stackoverflow.com/questions/22410538/error-control-may-reach-end-of-non-void-function-in-c) – Adrian Mole Apr 16 '20 at 17:31

1 Answers1

0

Your function returns a pointer. Since the function returns something, and that something is likely being used somewhere else in your code, it must return a value in any possible case. Your function however does not do this, since only the last branch has a return statement. If you somehow enter if (q.list == NULL) you have no return statement to execute.

To fix this, return something meaningful (NULL is a good choice to indicate an error):

void *returnMin(PQueue q){
  if (q.list == NULL){
    printf("List is empty.\n");
    return NULL;
  } else if (q.list->head == NULL){
    printf("List is empty.\n");
    return NULL;
  } else {
    return q.list->head;
  }
}
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • The C standard does not require a non-void function to return a value. However, if the return value of the function is used, the standard does not define the behavior. If the calling function does not use the return value, the behavior is defined. – Eric Postpischil Apr 16 '20 at 17:54
  • Wait really @EricPostpischil? That got me, I thought it did. Thanks. I suppose it makes sense to allow stuff like `exit()` being called in a function, or other functions like the libc wrapper for `execve`. – Marco Bonelli Apr 16 '20 at 18:06