I was reading my textbook for my computer architecture class and I came across this statement.
A second important distinction between the logical operators '
&&
' and '||
' versus their bit-level counterparts '&
' and '|
' is that the logical operators do not evaluate their second argument if the result of the expression can be determined by evaluating the first argument. Thus, for example, the expressiona && 5/a
will never cause a division by zero, and the expressionp && *p++
will never cause the dereferencing of a null pointer. (Computer Systems: A Programmer's Perspective by Bryant and O'Hallaron, 3rd Edition, p. 57)
My question is why do logical operators in C behave like that? Using the author's example of a && 5/a
, wouldn't C need to evaluate the whole expression because &&
requires both predicates to be true? Without loss of generality, my same question applies to his second example.