Booleans, Expressions, & If Statements

Boolean

A boolean is a data type true or false value.

Here are some things you can remember about a boolean.

  • A boolean is actually a single number, 1 or 0, with 1 being “true” and 0 being “false”.
  • Since boolean is only a 1 or 0, then it only takes up 1 byte of memory

Logical Expressions

A logical expression is some expression that can/will be simplified into a single “true” or “false” value.

This is typically done by using comparison operators, for example...

std::cout << 147 > 98;

This would print out 1 (remember, true = 1).

Logical Operators

Here is a list of important logical operators we use often:

  • ! - Not: Reverses the value of a boolean
  • && - And: Only evaluates to true if both arguments are true
  • || - Or: Evaluates to true if either side is true

Here is a list of comparison operators:

  • x > y - Returns true if X is greater than Y
  • x >= y - Returns true if X is great than or equal to Y
  • x == y - Returns true if X is equal to Y
  • x != y - Returns true if X is not equal to Y
  • x < y, x <= y - Self-explanatory, opposites of the first two

If Statements

An if statement is a statement that runs code only if the given expression evaluates to true, an example of this can be the following.

This is typically done by using comparison operators, for example...

if (x > y) { // Code here... }

This if statement will run all the code inside of the brackets if x > y evaluates to true.