简体   繁体   中英

Evaluation of && boolean operator

If i have the following if statement

if ( (row != -1) && (array[row][col] != 10) ) {
    ....
}

Where row is an int value and array is an int[][] object.

My question is, if this will throw an exception if row = -1 as the array won't have a -1 field, so out of bounds exception? Or will it stop at the first part of the if, the (row!=-1) and because that is false, it will ignore the rest? Or to be sure it doesn't throw exception, i should separate the above if statement into two?

(Pls, don't tell me to check this out for my self :) I'm asking here 'cause i wanna ask a followup question as well ...)

It will stop safely before throwing an exception

The && is a short-circuiting boolean operator , which means that it will stop execution of the expression as soon as one part returns false (since this means that the entire expression must be false).

Note that it also guaranteed to evaluate the parts of the expression in order, so it is safe to use in situations such as these.

It will not throw an exception. However, if row is < -1 (-2 for example), then you're going to run into problems.

It will stop at the first part of the if. Java uses short circuite evaluation .

No, It wont. the compiler will not check the second expression if the first expression is false... That is why && is called "short circuit" operator...

通过&&调用短路评估 ,如果行检查失败,则继续评估没有意义。

Most programming languages short-circuit the test when the first expression returns false for an AND test and true for an OR test. In your case, the AND test will be short-circuited and no exception will occur.

Many programming languages have short-circuit evaluation for logical operators.

In a statement such as A and B , the language will evaluate A first. If A is false, then the entire expression is false; it doesn't matter whether B is true or false.

In your case, when row is equal to -1 , row != -1 will be false, and the short-circui the array expression won't be evaluated.

Also, your second question about the behavior of the array index is entirely language-dependent. In C, array[n] means *(array + n) . In python, array[-1] gives you the last item in the array. In C++, you might have an array with an overloaded [] operator that accepts negative indexes as well. In Java, you'll get an ArrayIndexOutOfBoundsException .

Also, you might need something like the following (or just use a try/catch).

boolean isItSafe(int[][] a, int x, int y) {
    boolean isSafe = true;
    if (a == null || a.length == 0 || x >= a.length || x < 0 || y < 0 || y >= a[0].length ) {
        isSafe = false;
    }
    return isSafe;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM