C语言 编译器警告 - 建议在用作真值的赋值周围加上括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5476759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compiler warning - suggest parentheses around assignment used as truth value
提问by F. P.
When I try to compile the piece of code below, I get this warning:
当我尝试编译下面的代码时,我收到了这个警告:
warning: suggest parentheses around assignment used as truth value
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;
}
回答by Erik
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 domake that mistake ;)
总有一天你会很高兴编译器告诉你,人们确实会犯那个错误;)
回答by geekosaur
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
回答by Carl Norum
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))

