http://www.perlmonks.org?node_id=1049774


in reply to Re: No warning when assiging to a variable
in thread No warning when assiging to a variable

Let's have a look at what gcc does:

/tmp>cat gcc-warn-assign.c int main(void) { int i,x,y; i=x=y=0; /* unintentional assignment inside if condition */ if (x=42) i++; if (x=y) i++; /* intentional assignment inside if condition, marked with ext +ra parentheses */ if ((x=42)) i++; if ((x=y)) i++; return i; } /tmp>gcc -Wall -pedantic gcc-warn-assign.c gcc-warn-assign.c: In function ‘main’: gcc-warn-assign.c:6:2: warning: suggest parentheses around assignment +used as truth value gcc-warn-assign.c:7:2: warning: suggest parentheses around assignment +used as truth value /tmp>gcc --version gcc (GCC) 4.5.2 Copyright (C) 2010 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There i +s NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR +POSE. /tmp>

So, what do we see here?

(Ignore i and i++, it's just dummy code.)

Possibly unintentional assignments inside if conditions cause warnings, no matter what is on the RHS of the assignment operator. The RHS may be a constant, or any other expression. It does not matter, and it should not matter.

If you want to write "especially clever" code, you still can assign inside an if condition without warnings, but you must wrap the assignment in semi-redundant parentheses to make your intention -- you want to test the truth of the result of the assignment -- clear to gcc. And the code is still compatible with other C compilers that do not know the extra parentheses trick, they just ignore the redundant parentheses.

I think Perl with warnings enabled should behave the same: Warn if a variable is assigned anything, constant or not, inside the condition of if and friends, because it is likely a bug. And don't warn only if the assignment has extra parentheses indicating someone wanted to write "especially clever" code.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)