简体   繁体   English

编译器警告 - 建议用作真值的赋值括号

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

When I try to compile the piece of code below, I get this warning: 当我尝试编译下面的代码时,我收到此警告:

warning: suggest parentheses around assignment used as truth value

Why does this happen? 为什么会这样? This is a rather common idiom, I believe. 我相信这是一个相当普遍的习语。 I even use something like it earlier on my code. 我甚至在我的代码中使用了类似的东西。

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

    return NULL;
}

Be explicit - then the compiler won't warn that you perhaps made a mistake. 明确 - 然后编译器不会警告您可能犯了错误。

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

or 要么

while ( (list = list->next) )

Some day you'll be glad the compiler told you, people do make that mistake ;) 有一天你会很高兴编译告诉你,人们确实犯了这个错误;)

While that particular idiom is common, even more common is for people to use = when they mean == . 虽然这个特定的习惯用法很常见,但更常见的是人们使用=当他们的意思是== The convention when you really mean the = is to use an extra layer of parentheses: 你真正意味着=的惯例是使用一个额外的括号层:

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

It's just a 'safety' warning. 这只是一个“安全”警告。 It is a relatively common idiom, but also a relatively common error when you meant to have == in there. 这是一个相对常见的习惯用语,但当你打算在那里使用==时,这也是一个相对常见的错误。 You can make the warning go away by adding another set of parentheses: 您可以通过添加另一组括号来消除警告:

while ((list = list->next))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 警告:建议在赋值周围使用括号作为真值 [-Wparentheses] - warning: suggest parentheses around assignment used as truth value [-Wparentheses] 不断收到警告“建议在 '||' 内的 '&&' 周围加上括号适用于 C 程序 - Keep getting warning "Suggest parentheses around '&&' within '||' for C program GCC:在无法解决自己的比较括号周围建议括号 - GCC: suggest parentheses around comparison parentheses not able to solve myself 当赋值(括在括号中)用作真值时,强制 GCC 引发错误 - Force GCC to throw an error when an assignment (wrapped in parenthesis) is used as truth value GCC4.8 版本 建议在'!'的操作数周围使用括号 - GCC4.8 Version Suggest to use parentheses around operand of '!' 编译器警告:integer 转换为赋值指针 - Compiler warning: Conversion of integer to pointer at assignment 编译器#warning:打印枚举值 - Compiler #warning: print enum value C编译器错误-警告:赋值从指针进行整数转换而没有强制转换 错误:下标值既不是数组也不是指针 - C Compiler Errors - Warning: Assignment makes integer from pointer without a cast | Error: Subscripted value is neither array nor pointer gcc 结构分配警告缺少初始化器周围的大括号 - gcc struct assignment warning missing braces around initializer 摆脱编译器警告“警告:未使用调用结果” - Get rid of compiler warning “warning: result of call is not used”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM