C Programming Tutorial 52 – Logical Operators

In the last blog we went over If-Else Statements! Check it out first! Are you new here? Start at the beginning, Intro to C!

So far in in this series we’ve discussed the very basics of logic. In the very first blog over logic, I briefly introduced a topic called logical operators but I never went into a whole lot of detail. These allow us to make more complex conditionals, and that is what this entire blog is going to be about.

When we create a condition, it will evaluate as true or false. When we combine multiple conditionals, we create something known as a complex conditional.  Complex conditionals eventually always evaluate to either true or false.

The easiest way to explain is to go through an example.  

Let’s say you create a simple application that asks the user to sign in with a username and password. Once they sign in, the only way they can use the app is if they’ve either verified their email or verified their phone number.  You could write a conditional like this in English:

Well, the computer wouldn’t understand this, but this is a good starting point. You can see that there are in fact two conditions in one. The first is whether or not the user verified his or her email. The second is whether or not the user verified his or her phone number.

These are both pieces of a larger conditional. Each one will evaluate to true or false, but in order for the user to have to grant access, the entire thing has to be true or false. The final result of the condition ultimately depends on what is in the middle of the operators, which is known as the logical operator. In this case, we have an OR.

By convention, it is common when people discuss logical operators that the English word is in all caps.  

There are only 3 logical operators in C programming, AND (&&), OR (||) and NOT (!) 


Y = A || B 
True True True 
True False True 
False True True 
False False False 


Y = A && B 
True True True 
True False False 
False True False 
False False False 


Y = !A 
True False 
False True 

To make our example more computer sciency, we could write it as this:

where emailVerified() and phoneVerified() are functions that return true or false. We’ll discuss how to do things like this later, but trust me for now that it is possible.

The user would get access if either or both are true. The or statement in C is known as an inclusive-or, which means both can be true at the same time, which is in contrast to something known as an exclusive-or.

NOT will take whatever the truth value is of something and negate it. So you could do something like !emailverified(), which would evaluate to true if the email is NOT verified.

In the upcoming blogs we will be going over more examples of how to use these operators and their precedence. Read the next blog!

Leave a Reply

Your email address will not be published. Required fields are marked *