首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >If-else问题

If-else问题
EN

Stack Overflow用户
提问于 2010-08-21 18:09:13
回答 2查看 180关注 0票数 0

我正在学习队列,我偶然发现了这段代码。它来自一本书,所以我不能在这里张贴全部代码,但我所张贴的就足够了。不仅仅是一个问题,我只是想确认我对这段代码的理解是否正确。

在函数delete_ap()中,'if‘语句调用qretrieve()函数,并将其返回值存储在指针'p’中。我的问题是:如果返回的值不是NULL,那么' If‘语句也会被执行,不是吗?因此,一个值仍然存储在'p‘中,我们可以只打印这个值,而不使用本例中使用的'else’语句。

谢谢!

代码语言:javascript
复制
/* 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];
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-08-21 18:19:02

这与以下内容相同:

代码语言:javascript
复制
char *p = qretreive(); // <-- will always execute
if(p==NULL) 
  return; // <-- will not execute the next line if p is invalid
printf("%s\n", p);
票数 1
EN

Stack Overflow用户

发布于 2010-08-21 18:16:32

使用return语句,而不是将函数的其余部分放在else块中。

也就是说,只有在p != NULL的情况下,执行才会到达printf

注意:许多人认为,在代码中间返回会使代码难以阅读,并且容易出现错误,因为太少了通常在方法结束时进行的清理。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3537210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档