2010-08-21 51 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