2010-08-21 54 views
0

我正在学习队列,我碰到这段代码。它来自一本书,所以我不能在这里发布整个代码,但是我发布的内容就足够了。不仅仅是一个问题,我只想确认我对这段代码的理解是否正确。如果 - 其他问题

在函数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]; 
} 
+0

你能在这里包的代码位代码块?编辑你的文章,选择所有的代码,然后点击看起来像两行0和1的按钮。这是不可能的,否则... – Stephen 2010-08-21 10:10:43

+0

对不起,我忘了包装它。 感谢您编辑KennyTM。 – Naruto 2010-08-21 10:14:52

+1

谁写这本书写*丑*代码。 – James 2010-08-21 10:18:33

回答

1

这是一样的:

char *p = qretreive(); // <-- will always execute 
if(p==NULL) 
    return; // <-- will not execute the next line if p is invalid 
printf("%s\n", p); 
+0

! 它解决了我的问题。 – Naruto 2010-08-21 10:21:11

1

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

也就是说,如果p != NULL执行将只达到printf

注意:许多人认为代码中间的返回会导致代码难以阅读,并且由于缺少通常在方法结束时完成的清理而导致错误。

+0

是的,当'p'= NULL时'return'语句被执行。但是,如果'p'!= NULL,那么if语句也会被执行(但不是'return'语句,因此一个值被存储在'p'中。< - 这是否正确? – Naruto 2010-08-21 10:20:19

+0

感谢您的回应。 – Naruto 2010-08-21 10:22:39

+0

是的,“value”就像在“pointer”中那样,如果函数调用的返回值是NULL,那么NULL将被存储在p中,(如果p之前有一个值,那么重要的) – 2010-08-21 10:25:00