Reputation: 2724
I'm having trouble figuring why this isn't working...
if (index != 10 || index != 0) {
If index = 0
the function is still allowed in, why?
Upvotes: 0
Views: 116
Reputation: 53
You should replace the || with a &&.Not to get confused with the || which is OR operator and is evaluated true
if any of the conditions aretrue
while the && AND operator evaluates to a true
if and only if all the conditions are true
.
Upvotes: 0
Reputation: 1411
If index
evaluates to a number, one of those conditions will always be true.
Try
if (!(index == 0 || index == 10)) {
...
}
Upvotes: 1
Reputation: 4211
Because you are using an OR e.g. ||. So first of all it says does index != 10 which is true since it equals 0 and it therefore proceeds into the conditional.
You would need to change it to (index != 10 && index != 0).
Upvotes: 2
Reputation: 463
Yep, it will, since using || means it will run if ANY of the 2 conditions are true. Hence, since 0 is not 10, it will run, because when using || only 1 of the conditions needs to be satisfied.
If you want it to not be allowed, use &&
instead of ||
, this way it will only run if both conditions are satisfied
Upvotes: 1
Reputation: 349252
When index is zero, it is not ten.
The double pipe is a logical OR operator. The expression returns true when either the left, or the right side is true.
If you intend to return false when index is not 10 and zero, use the logical AND, &&
:
if (index != 10 && index != 0) {
Upvotes: 5