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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With