Sometimes I want to do something like this (with i and j being ints).
(if i==4 && j==9)
{
...
}
Where it’ll go through the brackets if i equals 4 and j equals 9. I’ve been using a single ampersand (&) instead of a double one and my code’s been compiling and running.
Is it doing the same thing as a double ampersand &&, and if not what has it been doing?
Edit: Oh and I’ve been doing the same thing with or, using ‘|’ instead of ‘||’
Presumably you mean
if (i==4 && j==9).Under the circumstances, changing this from
&&to&shouldn’t change much. The big thing that’ll change is that with&&, thej==9would only be evaluated if thei==4part was true, but with&, they’ll both be evaluated regardless.When you have something like
if (x != NULL && x->whatever ...)you want to ensure that the second part (that dereferencesx) is only evaluated ifxis not a null pointer. In your case, however, comparing what appear to beints is unlikely to produce any problems.It’s also possible to run into a problem when you’re dealing with something that may produce a value other than
1to signaltrue. Again, it’s not a problem here because==will always produce either0or1. If (for example) you were usingisalpha,islower, etc., from<ctype.h>, they’re only required to produce0or non-zero values. If you combined those with a&, you’d get a bit-wiseorwhich could produce 0 for two non-zero inputs (e.g.,1 & 2 == 0, but1 && 2 == 1).When you use bitwise
andon the results from==, you’re going to get0 & 0or0 & 1or1 & 0or1 & 1.1 & 1will yield1(true). All the others will yield 0 (false) — just like&&would have.