[英]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.