Operators
There are four main types of operator in C++:
- Arithmetic
- Relational
- Logical
- Bitwise
Assignment
The assignment operator = can be used in any expression. The normal form is:
variable_name = expression;The left part must be a variable or pointer. The left part cannot be a function or constant.
In docs we might see lvalue and rvalue.
lvalue is what appears on the left side of the assignment (usually the variable name).
rvalue is what appears on the right side and what will be assigned to the variable.
Arithmetic
- is subtraction
+ is addition
* is multiplication
/ is division
% is modulus (remainder when dividing)
Increment / Decrement
Like in Python you can increment and decrement variables.
To add 1 to a variable, use
++variablename;To subtract 1 from a variable, use
--variablename;You can use the increment and decrement operators before or after the variable name. If it is used before the name, the increment or decrement happens before the variable value is fetched. If it is used afterwards, the increment or decrement happens after the variable value is fetched. So, if we ran
y = ++x;then y would be set to 1 more than x. x would remain unchanged. If we ran
y = x++;then y would be set to the value of x, and x would be incremented.
Relational
Relational operators define a relationship between two values.
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
== is equal to
!= is not equal to
Relational operators return a Boolean value.
Logical
Logical operators describe how previous relationships must be connected.
&& is AND
|| is OR
! is NOT
&& is true if both operands are true.
|| is true if either operand is true.
! has only one operand (on the right) and it inverses a the value (from true to false and vice versa).
True and False
True is any value other than zero. False is zero. Expressions using relational and logical operators return 0 if the result is false and 1 if it is true. In C++ we can use the bool data type and the Boolean constants true and false. (not capitalised unlike Python)
Bitwise
Bitwise operations test, set or shift the actual bits in a byte or word.
& is AND
is OR
^ is XOR (Exclusive OR)
~ is One's complement (NOT)
>> is shift right
<< is shift left