61

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; } 
4
  • 2
    You're free to turn off the warning, or rather leave it off since it's off by default... Commented Mar 29, 2011 at 17:54
  • 4
    I'm sort of absent minded so I am thankful for pedantic, -Wall, -Wextra, -Wshadow and the like Commented Mar 29, 2011 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 ==... Commented Mar 29, 2011 at 18:08
  • Possible duplicate of warning: suggest parentheses around assignment while (*(arg_to++) = *(arg_from++)); Commented Jan 19, 2018 at 22:57

4 Answers 4

95

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

Sign up to request clarification or add additional context in comments.

4 Comments

People do! For this very reason, I used to write if (0 == varName) in C, so that I could get an error message if I mistyped it.
@jpaugh That is called a Yoda condition. It has a Wikipedia page :)
@LarsNyström Pleased I am to know this!
@jpaugh Which is very stupid syntax. There is warning for rare cases when you can do such error.
67

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 

1 Comment

I've seen this convention, and never understood why it was used.
24

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

Comments

0

This error may also occur when

if(x = 10) // this is incorrect if(x == 10) // this is correct 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.