If-else problem
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.
开发者_Python百科 rpos:holds the index of the next item to retrieve.*/
{
printf("No more appointments.\n");
return NULL;
}
rpos++;
return p[rpos-1];
}
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);
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.
精彩评论