Monday, 22 October 2018

Logical Operators in C

This is another lesson in C for programmers who are new to the language. Here I want to summarise logical operators which you can use to test if some condition is true or false.

The && operator means ‘and’ and the || operator means ‘or’. These are called ‘logical operators’. Logical operators can help you chain together conditions when you want to take some action only when all of a set of conditions are true or when any one of a set of conditions is true. For example, you might want to offer a discount to customers only when they have bought goods worth more than 100 dollars and they have also bought the deal of the day. In code these conditions could be evaluated using the logical and (&&) operator, like this:

 if ((valueOfPurchases > 100) && (boughtDealOfTheDay))

But if you are feeling more generous, you might want to offer a discount either if a customer has bought goods worth more than 100 dollars or has bought the deal of the day. In code these conditions can be evaluated using the logical or (||) operator, like this:

 if ((valueOfPurchases > 100) || (boughtDealOfTheDay))

Logical operators test Boolean values. A Boolean value can either be true or it can be false. Some programming languages have a special Boolean data type. C does not. In C, any non-zero value such as 1 or 100 is evaluated as true. A zero value is evaluated as false.

It is possible to create quite complex conditions by chaining together tests with multiple && and || operators. Be careful, however. Complex tests are often hard to understand and if you make a mistake they may produce unwanted side effects. In addition, just as when you are using arithmetic operators, you may avoid ambiguity by grouping the individual ‘test conditions’ between parentheses.

The ! operator can be used to negate a condition. So the test !( a == b) (‘not a equals b’) is equivalent to (a != b) (‘a is not equal to b’). Similarly this test…

 (number_of_children != 0)

…could be rewritten like this:

!(number_of_children == 0)

NOTE: If you are new to C, you may want to start with lesson 1 in this series: http://www.bitwisemag.com/2017/02/introduction-to-c-programming.html
And if you want to learn C in more depth, why not sign up to my online video course – C Programming for beginners. See here: http://www.bitwisemag.com/2017/01/learn-to-program-c-special-deal.html