Reason for the existence of non-short-circuit logical operators

后端 未结 6 1216
借酒劲吻你
借酒劲吻你 2020-11-28 08:16

When used with boolean operands, & and | become logical operators per Section 15.22.2 of the JLS. Unlike &&

6条回答
  •  再見小時候
    2020-11-28 08:29

    There are instances where the components of a boolean expression involve operations that you'd want to have executed in all cases. Consider the following example of checking a password for validity:

    while ( !password.isValid() & (attempts++ < MAX_ATTEMPTS) ) {
    
        // re-prompt
    
    }
    

    If the second condition was not evaluated due to short-circuiting, attempts would never be incremented. Thus greater programmer flexibility is enabled.

提交回复
热议问题