-2

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.

kyrill
  • 986
  • 10
  • 27
  • This is kind of vague. You want to know why they were created, even though you found what their usage is? – Carcigenicate Sep 28 '18 at 11:46
  • Assembly / cpu hardware *doesn't* have logical operators, so [tag:cpu-architecture] doesn't really apply. This is a high-level language design question. (I'm assuming you're talking about short-circuit evaluation operators like C's `a && b` which treats both sides as boolean, not bitwise-and `a & b`.) Can you explain what the CPU-architecture aspect of this question is, and why you added that tag? – Peter Cordes Sep 28 '18 at 12:00
  • 1
    There are no challenges to face. They are for convenience only. Alan Turing showed they are not needed with his single instruction: `copy, minus, branch on negative`. – shawnhcorey Oct 03 '18 at 12:45

1 Answers1

1

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.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847