Search code examples
programming-languageslogical-operatorslanguage-design

Why were Logical Operators created?


Almost all programming languages are having the concept of logical operator I am having a query why logical operators were created. I googled and found its created for condition based operation, but that's a kind of usage i think.

I am interested in the answer that what are the challenges people faced without this operator. Please explain with example if possible.


Solution

  • I am interested in the answer that what are the challenges people faced without this operator.

    Super-verbose deeply nested if() conditions, and especially loop conditions.

    while (a && b) {
        a = something;
        b = something_else;
    }
    

    written without logical operators becomes:

    while (a) {
        if (!b) break;   // or if(b){} else break;  if you want to avoid logical ! as well
        a = something;
        b = something_else;
    }
    

    Of if you don't want a loop, do you want to write this?

    if (c >= 'a') {
        if (c <= 'z') {
            stuff;
        }
    }
    

    No, of course you don't because it's horrible compared to if (c >= 'a' && c <= 'z'), especially if there's an else, or this is inside another nesting. Especially if your coding-style rules require 8-space indentation for each level of nesting, or the { on its own line making each level of nesting eat up even more vertical space.


    Note that a&b is not equivalent to a&&b: even apart from short-circuit evaluation. (Where b isn't even evaluated if a is false.) e.g. 2 & 1 is false, because their integer bit patterns don't have any of the same bits set.

    Short-circuit evaluation allows loop conditions like while(p && p->data != 0) to check for a NULL pointer and then conditionally do something only on non-NULL.

    Compact expressions were a big deal when computers were programmed over slow serial lines using paper teletypes.


    Also note that these are purely high-level language-design considerations. CPU hardware doesn't have anything like logical operators; it usually takes multiple instructions to implement a ! on an integer (into a 0/1 integer, not when used as an if condition).

    if (a && b) typically compiles to two test/branch instructions in a row.