tags:

views:

92

answers:

2

I'm learning queues and I came across this piece of code. It's from a book, so I can't post the whole code here but what I'm posting will be sufficient. More than a problem, I just want to confirm that whether my understanding of this code is correct or not.

In the function, delete_ap(), the 'if' statement calls qretrieve() function and stores its return value in pointer 'p'. My problem is: If the value returned is not NULL, then too the 'if' statement is executed, isn't it? So a value is still stored in 'p' and we can just print this value without using an 'else' statement as used in this example.

Thanks!

/* Delete an appointment from the queue. */
void delete_ap(void)
{
  char *p;
  if((p=qretrieve()) ==NULL) return;
  printf("%s\n", p); <--Problem is in this line and the one above it.
}

/* Retrieve an appointment. */
char *qretrieve(void)
{
  if(rpos==spos) /* spos:holds the index of the next free storage location.
                    rpos:holds the index of the next item to retrieve.*/

   { 
    printf("No more appointments.\n");
    return NULL;
   }
  rpos++;
  return p[rpos-1];
}
+1  A: 

The return statement is used instead of putting the rest of the function in an else block.

That is, the execution will only reach printf if p != NULL.

Note: Many people argue that returns in the middle of the code makes the code hard to read and prone to bugs due too missing cleanup that is usually done at the end of the method.

Albin Sunnanbo
Yes, the 'return' statement is executed when 'p'=NULL. But if 'p'!=NULL then too the if statement is executed (but not the 'return' statement, and therefore, a value is stored in 'p'.<-- Is this correct?
Naruto
Thanks for the response. You've been very helpful.
Naruto
Yes, "value" as in "pointer". Well, if the return value from the function call is NULL then NULL will be stored in p, (important if p had a value before).
Albin Sunnanbo
+1  A: 

This is the same as:

char *p = qretreive(); // <-- will always execute
if(p==NULL) 
  return; // <-- will not execute the next line if p is invalid
printf("%s\n", p);
Zaki
Thanks!It solved my problem.
Naruto