簡體   English   中英

編譯器警告 - 建議用作真值的賦值括號

[英]Compiler warning - suggest parentheses around assignment used as truth value

當我嘗試編譯下面的代碼時,我收到此警告:

warning: suggest parentheses around assignment used as truth value

為什么會這樣? 我相信這是一個相當普遍的習語。 我甚至在我的代碼中使用了類似的東西。

struct PIDList* 
getRecordForPID(struct PIDList* list, pid_t pid) {
    while(list = list->next)
        if (list->pid == pid)
            return list;

    return NULL;
}

明確 - 然后編譯器不會警告您可能犯了錯誤。

while ( (list = list->next) != NULL )

要么

while ( (list = list->next) )

有一天你會很高興編譯告訴你,人們確實犯了這個錯誤;)

雖然這個特定的習慣用法很常見,但更常見的是人們使用=當他們的意思是== 你真正意味着=的慣例是使用一個額外的括號層:

while ((list = list->next)) { // yes, it's an assignment

這只是一個“安全”警告。 這是一個相對常見的習慣用語,但當你打算在那里使用==時,這也是一個相對常見的錯誤。 您可以通過添加另一組括號來消除警告:

while ((list = list->next))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM