At least three times today I've seen questions about the following kind of if
statement:
if (var != "x" || var != "y" || var != "z")
The most recent is Why is my if statement activating when it is not supposed to?. I've seen it in C, JavaScript, PHP, Python, and other languages.
This is one of the most common errors people make in writing if
statements. The answer is simply to change ||
to &&
. So there are thousands of duplicates. But when I was trying to find one so I could mark that question as a duplicate, I couldn't; phrases like "if statement" are just too common. I'll bet there's already a really good answer out there, does anyone have a link to one that could serve as the canonical answer?
Actually, the answer posted in the above question explains the issue pretty well. So if no one has a better one to suggest, I'll probably start using that.
There are similar issues with:
if (var == "x" || "y" || "z")
and
if (var != "x" || "y" || "z")
There are some languages where this actually works, but in most of the common languages it doesn't do what the programmer intends. Again, if someone has a canonical question for these, please share it.
&&
vs||
) should be closed as a typo. The latter already has language-specific solutions, they just aren't connected yet.while
ordo/while
loop, than it does in anif
statement. For example (shamelessly plugging my own answer), there's stackoverflow.com/q/22397105 and many others like it.