# C Logical Operators Cheat Sheet

Symbol Name Description
Bit-wise
& Bit-wise AND Operator
| Bit-wise Non-exclusive OR (otherwise just known as Bit-wise OR)
^ Bit-wise Exclusive OR Do not think this sign is the mathematical sign for an exponential, in-fact, in c, there is no symbol for an exponential operation.
Logical
&& Logical AND Operator Guarantees short-circuit evaluation.
|| Logical Non-exclusive OR (otherwise just known as Logical OR) Guarantees short-circuit evaluation.
^^ Logical Exclusive OR TRICKED YOU! This doesn’t exist in C! What? Why? See below for more information…

# The Conditional Operator (?:)

The conditional operator is the only tenary operator (operator which takes 3 operands) in the C programming langauge. Functionally, it performs the same thing as an if/else statement. It uses the syntax:

If the condition is true, this whole code segment gets replaced with resultIfTrue, if the condition is false, the code segment gets replaced with resultIfFalse. Here is a real example:

However, the conditional operator forms an expression, not a statement, which means it can be used in different places to an if/else.

It can be used to declare a const that is conditional on some other variable, as shown in the example below:

# Logical Short-Circuit Evaluation

Both logical OR ( ||) and logical AND ( &&) guarantee short-circuit evaluation. This means that the second argument is only evaluated if it needs to be to determine the outcome of the logical operation.

This makes it possible to do things like this:

You should be able to see that if x was NULL, than calling x-&gt;IsValid() has undefined behaviour. However, this statement is valid because of short-circuit evaluation. x-&gt;IsValid() will only be called if x! = NULL evaluates to true and the program needs to find x-&gt;IsValid() to determine the outcome of the expression.

# Why Is There No Logical Exclusive OR (^^)?

The C programming language does not provide us with a logical exclusive OR operator (which would presumably be ^^).

However, we can get the same effect by writing:

If you happen to know that a and b can only be boolean (i.e. or 1), then this can be simplified to:

Notice that in the first example, you need the ! symbols to normalise both a and b into booleans.

# Conditional Operator

The conditional operator, ? is used to write the equivalent of an if/else statement, but in a shorter format. It allows you to write an if/else as an expression, rather than a statment. This allows it to be used on the RHS of a statement.

Conditional operators can be chained together.