Oops, correction.
Code: Select all
if(test = 0){
print "I won't print because of the assignment"
}
This would normally run if test had been set to anything besides zero as an if statement evaluates true if not 0 (could be any other number).
Code: Select all
if(test = 0){
print "I won't print because the variable has been assigned to zero"
}
if(test = 2){
print "I will print because the variable has been assigned a non-zero value"
}
Any common-case reasons not to do so besides being explicit? That would be another way of avoiding the original unintended consequence.
The original code that I noticed the problem with did not test whether variables were equal to one or zero, but other integer values in a pseudo case statement. I wasn't sure whether or not hoc code supported case statements so instead I just used a few if statements, in which I cared whether or not my variable was equal to 2, or 3, not just that it wasn't zero.
Regarding Ted's code:
Code: Select all
i = 9
while ((i = i+1) < 20) print i
I think that makes a lot of sense in a loop, although some Matlab habits would lend me to changing the value of "i" inside the loop, and even then I would use a for loop in the above case as I typically only use while loops when there is some condition inside of the loop that would lead to alterations in the order. Overall though, I agree.
Lots of working code depends on this property of the assignment statement,so it isn't going to be changed
I'll buy that. I'll just have to be more careful. Although, I still think it is poor code, and shouldn't be included in any language to allow assignment of a variable in an if statement.