C Language

To share this page click on the buttons below;

Logical operators

Logical operators are strictly related with Boolean Algebra. The Boolean Algebra is the algebra that deals only with 2 values: true and false (or 1 and 0). In that kind of algebra the variables can just assume those 2 values and nothing else.

The Boolean Algebra defines a set of operators that allow the manipulation of the boolean variable like the 4 algebric operations do for numbers:

  • AND   operator
  • OR   operator
  • NOT   operator

The boolean NOT

The boolean NOT operator can be applied to just one single boolean variable and operates in a very simple way: if the variable is true the not operator makes it false and if it is false makes it true.

The boolean AND

The boolean AND operator is applied to a pair of boolean variables. Suppose that you have a boolean variable A and boolean variable B: the result of A AND B depends on the values of A and B following the rules summarized in the next table

A B A AND B
True True True
True False False
False True False
False False False

That is pretty simple: A AND B is True only if A and B are both True and false otherwise.

The boolean OR

The boolean OR operator is applied to a pair of boolean variables too. If you have a boolean variable A and boolean variable B the result of A OR B depends on the values of A and B following the rules summarized in the next table

A B A AND B
True True True
True False True
False True True
False False False

Again it is pretty simple: A OR B is True if either A or B are True and false otherwise.

The logical C operator

The logical C operators are simply the implementation in C language of the Boolean operators. They are important because they allow the possibility to make complex conditions starting from the relational operators.

Suppose that you want to verify that an integer variable a is lower than 5 and higher than 2: that condition can be expressed using logical operators as (a < 5 AND a > 2).

The C language defines the following reserved words as logical operators:

  • &&   operator is the boolean AND
  • ||   operator is the boolean OR
  • !   operator is the boolean NOT

Remember that in C logic 0 is false and everything else is true. So if you have a variable a which has a value of 32 and you write !a (logic not) you get 0.

While building big boolean expression I would suggest to always use parenthesis to specify the proper order of execution of the various operators.

To share this page click on the buttons below;