59

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;
}
Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
F. P.
  • 5,018
  • 10
  • 55
  • 80
  • 1
    You're free to turn off the warning, or rather leave it off since it's off by default... – R.. GitHub STOP HELPING ICE Mar 29 '11 at 17:54
  • 4
    I'm sort of absent minded so I am thankful for pedantic, -Wall, -Wextra, -Wshadow and the like – F. P. Mar 29 '11 at 18:03
  • 2
    Well you can add `-Wno-parentheses` (I believe that's the right one) to disable this specific warning. However, if you're that absent-minded, be careful not to write `=` instead of `==`... – R.. GitHub STOP HELPING ICE Mar 29 '11 at 18:08
  • Possible duplicate of [warning: suggest parentheses around assignment while (\*(arg\_to++) = \*(arg\_from++));](https://stackoverflow.com/questions/48334266/warning-suggest-parentheses-around-assignment-while-arg-to-arg-from) – jpaugh Jan 19 '18 at 22:57

3 Answers3

90

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 ;)

Erik
  • 88,732
  • 13
  • 198
  • 189
64

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
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
geekosaur
  • 59,309
  • 11
  • 123
  • 114
23

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))
Carl Norum
  • 219,201
  • 40
  • 422
  • 469