Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix the Werror=parentheses (suggest parentheses around assignment) error?

Tags:

c++

c++11

I have a line of code which does both assignment and condition. I could split it into two lines but I'm just curious about the error message thrown.

  if ( parameters->__size = m_Elements.size() ) 

Got this error: suggest parentheses around assignment used as truth value [-Werror=parentheses]

I tried:

   if ( (parameters->__size) = (m_Elements.size()) )

The error doesn't go away. But I feel I have done what I was prompted to do and added parentheses around the assignment. Why doesn't the error go away? What am I missing?

like image 294
badri Avatar asked Dec 18 '22 12:12

badri


2 Answers

To convince the compiler that the assignment is really what you want, you need to enclose the whole expression in parentheses, like this:

    if ( ( parameters->__size = m_Elements.size() ) ) 
    //...

Without this, the compiler thinks that you may have made a mistake, using assignment (=) instead of the comparison (==) operator.

like image 200
Adrian Mole Avatar answered Jan 04 '23 22:01

Adrian Mole


The warning suggests you to put parentheses around the assignment expression, not around the individual operands. You can silence it via

if ( ( parameters->__size = m_Elements.size() ) )
  // ^                                        ^   

However, ask yourself if this is really any better than the original. I suppose you turned on the warning for a reason and the suggested fix does indeed silence the warning, but the code can still cause the same confusion as before for a reader. You can do this instead:

parameters->__size = m_Elements.size();
if (parameters->__size)
like image 30
463035818_is_not_a_number Avatar answered Jan 05 '23 00:01

463035818_is_not_a_number