The logical operators are also called Boolean operators. The name Boolean comes from George Boole, who first described the branch of mathematics that works with truth values, instead of numbers.
Advertise on this site. I promise you will like the rates :)
C has three logical operators:
They all work with truth values and return as result truth value.
Note:If you are coming from another language like Java or C#:
Do not confuse the boolean operators && and || with the operators & and |. In C, the & and | operators are only bitwise.
Recall from the data types lesson, that C recognizes as true any value that is not 0 and the 0 is false.
Also, if you are writing C99 compatible code, you can and should use the <stdbool.h> and the macros that it defines: true and false. For more information see the data types lesson.
The boolean operator && returns true only when all its operands are true. let's visualize this:
which is the same as
Let's create an example that asks the user for his/her age and gender and determines if that is a woman under 30.
In this example we use boolean values returned by the comparison operators "<" and "==".
The logical operator || returns true, if at least one of the operands is true. If they are all false, it returns false. Here's its truth table:
which is equivallent to
Let's make another short example: Input two numbers and check if at least one of them is not a zero:
Here is how this code works for me:
Remember: in the C language 0 means false and anything else is true. That is why we don't need to compare the numbers to 0.
The code from the examples above is also available on Git Hub.
The negation always returns the opposite of its operand. NOT true is false. NOT false is true. Simple logic ;)
The boolean operators have different precedence. The operations are done from left to right and from the highest to the lowest precedence.
From highest to lowest they are:
This means that:
!true || true && !false
will be equal to true. The first operation to be evaluated is the the highest precedence - the first logical NOT. This will transform the above expression to:
false || true && !false
Now the && will be evaluated, because it has a higher precedence, compared to the logical OR. However, the right operand of the logical AND contains logical NOT which has an even higher precedence, so first that will be calculated:
false || true && true
Only now the logical AND can return its result:
false || true
.. and finally the logical OR will return true.
To change the order of execution we use braces. Even if braces are not necessary to change the order of evaluation, they can be used to make it more obvious what is expected to happen. It is a good coding practice to place braces in complex expressions (more than 2 operators in one statement).
The following expression will first do the operations in the braces and only then it will do the rest:
(true || false) && !false