domingo, 9 de agosto de 2020

Operators and if conditional in C++

In C++, an operator is a symbol that performs a certain mathematical operation. The main categories of operators are arithmetic, relational, and logical.

  • Arithmetic Operators

OperatorAction
+Addition
-Subtraction
*Multiplication
/Division
%Remainder of division

Arithmetic operators are used in mathematical expressions. The line below shows an example of an expression whose result will be stored in the Result variable using the assignment operator =.
Result = 10 * 3 + 5;

There are some shorthand operators that are widely used in C++. For example, we have the increment operator ++ which adds 1 to the variable, and the decrement operator -- which subtracts 1, as shown below:
Count++;
Count--;

//It's equivalent to: 

Count = Count + 1;
Count = Count - 1;

Other shorthand operators are the ones that use an arithmetic operator together with the assignment operator:
Count += 15;

//It's equivalent to: 

Count = Count + 15;

  • Relational Operators

OperatorAction
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to
==Equal to
!=Not equal to

Relational operators perform a comparison between two values and return a Boolean value (true or false) as a result of the comparison.

Note that the equality operator is ==. Take care not to be confused with the assignment operator that is just =.
 
  • Logical Operators

OperatorAction
||OR
&&AND
!NOT

Logical operators perform an operation between Boolean values and return a Boolean value (true or false) as a result of the operation. The main logical operations are OR, AND, NOT.

The logical operator || (OR) returns true if any of the Boolean values are true. The logical operator && (AND) returns true only if all Boolean values are true. The logical operator ! (NOT) inverts the Boolean value.

  • Conditional if

The if statement evaluates an expression and executes a block of code if the result of the expression is true. It can be used in conjunction with the else statement that executes a code block if the result of the expression is false.

This is the format of the if ... else:
if (expression) 
{
  // if code block. Executed if the expression is true.
} 
else   // optional
{
  // else code block. Executed if the expression is false.
}

The if ... else statement is equivalent to the Blueprint Branch node:



In the next article, we will use the operators and the if statement to create a new function in the ATutoProjectGameMode class.