Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Understanding "logical OR" and "logical AND" in programming languages
Parent
Understanding "logical OR" and "logical AND" in programming languages
Many programming languages either have keywords like or
and and
used for logic, or equivalent operators such as ||
or &&
- which are referred to as "logical or" and "logical and" respectively in the language documentation. However, these tools don't seem to work in a natural or expected way for many beginners. Which is to say: "translating" an English sentence into code, using or
or ||
to represent the English word "or", etc., commonly causes errors or gives the wrong result.
Why is this? What are the semantics of these operators, and how is that different from a natural-language understanding? And why are they called "logical"? (Are there other kinds?)
Post
One thing I'd like to add to Lundin and r.zwitserloot answers, which is something that I think is rather important:
The "or" in programming is inclusive. The "or" in most languages (all those I know of: "or", "ou", "ó", "order"...) is exclusive.
If we look at the truth tables of the AND, OR, and XOR we have:
A B AND OR XOR
-----------------
0 0 0 0 0
1 0 0 1 1
0 1 0 1 1
1 1 1 1 0
^ ^
| |
| +--- language OR
|
+--- language AND
As we can see, in a programming language "if A or B ..." means that A can be true, B can be true, or A and B can be true. In our languages, if A and B are both true, we often don't use the work "or".
Do you want the blue or the red pill?
On top of that, in most programming languages, you do not have a logical XOR operator. You often have a bitwise XOR, though. Usually using ^
character, at least in C and derivatives.
One way I've seen people deal with the inclusive "or" in English is by using the "and/or" double conjunction: A and/or B ...
1 comment thread