我正在学习队列,我偶然发现了这段代码。它来自一本书,所以我不能在这里张贴全部代码,但我所张贴的就足够了。不仅仅是一个问题,我只是想确认我对这段代码的理解是否正确。
在函数delete_ap()中,'if‘语句调用qretrieve()函数,并将其返回值存储在指针'p’中。我的问题是:如果返回的值不是NULL,那么' If‘语句也会被执行,不是吗?因此,一个值仍然存储在'p‘中,我们可以只打印这个值,而不使用本例中使用的'else’语句。
谢谢!
/* 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];
}发布于 2010-08-21 18:19:02
这与以下内容相同:
char *p = qretreive(); // <-- will always execute
if(p==NULL)
return; // <-- will not execute the next line if p is invalid
printf("%s\n", p);发布于 2010-08-21 18:16:32
使用return语句,而不是将函数的其余部分放在else块中。
也就是说,只有在p != NULL的情况下,执行才会到达printf。
注意:许多人认为,在代码中间返回会使代码难以阅读,并且容易出现错误,因为太少了通常在方法结束时进行的清理。
https://stackoverflow.com/questions/3537210
复制相似问题