Two Hidden Bugs of Conditional Operators

      Comments Off on Two Hidden Bugs of Conditional Operators

Programmers create bugs, but experienced programmers should be familiar with their language and have best practices to avoid possible common bugs.

I found operators are sometimes easy to behave weirdly. Today I memo two bugs to help readers and myself avoid them in the future.

  1. == has higher precedence than && and || (most language like java or python).
    For example, expected == test1 && test2 will not compare expected with test1 && test2.

  2. Expressions behind && and || may have no chance to run.
    Example: I want to run three searches and see if any of them returns a true.

boolean result = false;
result = result || search(parameters_1);
result = result || search(parameters_2);
result = result || search(parameters_3);
if(result) {
    //do something
}

The problem is when search(parameters_1) returns true, result becomes true so search(parameters_2) and search(parameters_3) are not executed.
You may need to guarantee that all of the searches are executed (e.g. you need to record some data in the search, very common in bfs or dfs traversal algorithm), therefore you have to assign three variables to them. Note that result = search(parameters_1) || search(parameters_2) || search(parameters_3) does not guarantee the three executions either.

boolean result1 = search(parameters_1);
boolean result2 = search(parameters_2);
boolean result3 = search(parameters_3);
boolean result = result1 || result2 || result3;
if(result) {
    //do something
}