Operators

The chapters befor deals with variables and constants and now we use them with operators. It is not necessary to know all of them but they are all listed as reference book.

Assignment operator (=)

The assignment operator assigns a value to a variable.

Example:
inti = 1;

Always are assigned Values from right to left to the variable with the assignment operator.

Example:
intx = y;

In this example the value of variable x is assigned to value of y. By doin this has the variable x the same value as y.

Consider also that we are only assigning the value of y to x at the moment of the assignment operation. Therefore, if y changes at a later moment, it will not affect the new value taken by x.

Example:

1#include <iostream>
2using namespace std;
3
4int main() {
5    int x,y;     //x : ? | y : ?
6    
7    x = 7;      //x : 7 | y : ?
8    y = 4;      //x : 7 | y : 4
9    x = y;      //x : 4 | y : 4
10    y = 5;      //x : 4 | y : 5
11    
12    cout << "x = " << x << endl;
13    cout << "y = " << y << endl;
14    
15    return 0;
16}

This program prints on screen the final values of x and y (4 and 5, respectively). Notice how a was not affected by the final modification of y, even though we declared x = y earlier.

Assignment operations are expressions that means that an expression can be made of several operations or combined with other assignment operations.

Example:
inty = 6 - (x = 3);

In this expression, y is assigned the result of 6 subtract from 3 and the value of another assignment expression which has itself a value of 3. It is the same as:

Example:
intx = 3;
inty = 6 - x;

The result is the assignment of integer value 3 of variable y.

The next example is also valid in C++.

Example:
intx = y = z = 2;

It assigns 2 to the all three variables: x, y and z; always from right-to-left.

Arithmetic operators ( +, -, *, /, % )

In C++ are five arithmetic operators supported as following.

OperatorDescription
+addition
-subtraction
*multiplication
/division
%modulo

The operators at the above table like addition, subtraction, multiplication and division correspond literally to their respective mathematical operators. The modulo operator (%) is the division of two natural numbers with remainder.

Example:
intx = 5 % 2;

In the variable x assigning the value 1, since dividing 5 by 2 results in 2, with remainder of 1.

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

A compound assignment operator assigning the current value of a variable by performing an operation on it. That is the same like a result of an operation which is assigned to a variable.

ExpressionEquivalent to
x += y;x = x + y;
x -= 3;x = x - 3;
x /= y;x = x / y;
x *= y + 2;x = x * (y + 2);
x %= 2;x = x % 2;
x <<= y;x = x << y;
x >>= y;x = x >> y;
x &= y;x = x & y;
x ^= y;x = x ^ y;
x |= y;x = x | y;

Example:

1#include <iostream>
2using nanespace std;
3
4int main() {
5    int x = 3, y = 2;
6    
7    x *= (y + 1);
8    
9    cout << "x = 3" << endl << "x = 2" << endl;
10    cout << "x * (y + 1)" << endl;
11    cout << "3 * (2 + 1) = " << endl;
12    
13    return 0;
14}

Increment and decrement (++, --)

The increase operator (++) increment a stored value by one and the decrease operator (--) reduce a stored value by one. They are equivalent to +=1 and to -=1, respectively.


Example:
++x;
x += 1;
x = x + 1;

These three expressions are all equivalent in its functionality.

This three expressions may have produced different executable code in the early C compilers depending on which one was used. Nowadays through code optimizing by the compiler should produce the three expressions exactly the same executable code.

It exists a pecularity of this operators they can used as a prefix and as a suffix. That means that it can be written as ++x or as x++ to example. Both variances do the same thus increased a value by one but with an important difference, because the prefix type increased an expression to final and the suffix type increased the value that x had befor being increased by one. In a loop a suffix type increased after an iteration.


Example:
x = 3;//x contains 3
y = ++x;//x contains 4, y contains 4

In this Example, the value assigned to y is the value of x after being increased.

Example:
x = 3;//x contains 3
y = x++;//x contains 4, y contains 3

While in this Example, it is the value x assigned to y before being increased.

Relational and comparison operators (==, !=, >, <, >=, <=)

Two expressions can be compared using relational and equality operators. For example, to know if two values are equal or if one is greater than the other.

The result of such a settlement is either true or false.

Relational Operators:

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

It can be compared numeric constants, mathematician expressions, variables and expressions with assignment operations like ((a = 3) == b).

Example:
(1 == 2);//evaluates to false
(10 < 15);//evaluates to true
(7 != 3);//evaluates to true
(9 <= 9);//evaluates to true
(3 > 3);//evaluates to false
(a != b);//evaluates to false, since a is equal to b
(a - 10 > b * c);//evaluates to false, since a - 10 is less than b * c

Attention the comparision operator (==) is not equal to the assignment operator (=), because the assignment operator assign a value to its left variable (x = 1) and comparision operator check of equality.

Logical operators (!, &&, ||)

The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.

Example:
!(3 == 3);//evaluates to false because the expression at its right (3 == 3) is true
!(3 > 13);//evaluates to true because (3 > 13) would be false
!true//evaluates to false
!false//evaluates to true

The logical operators && and || are used when evaluating two expressions to obtain a single relational result.

The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise.

Truth Table:

&&Operand(AND)
aba && b
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

The operator || represents the Boolean logical term OR, which yields true if either of its operands is true, thus being false only when both operands are false.

Truth Table:

||Operand(OR)
aba || b
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

Example:
((2 == 2) && (7 < 4))//evaluates to false (true && false)
((2 == 2) || (7 < 4))//evaluates to true (true || false)

When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the combined relational result, ignoring the rest. Therefore, in the last example ((2 == 2) || (7 < 4)), C++ evaluates first whether 2 = 2 is true, and if so, it never checks whether 7 < 4 is true or not. This is known as short-circuit evaluation.


Operatorshort description
&&if the left-hand side expression is false, the combined result is false (the right-hand side expression is never evaluated).
||if the left-hand side expression is true, the combined result is true (the right-hand side expression is never evaluated).

This is mostly important when the right-hand expression has side effects, such as altering values:

((i < 5) && (++i < n)) { /*...*//* }//Attention the right-hand of this expression increments i

Here, the combined conditional expression would increase i by one, but only if the condition on the left of && is true, because otherwise, the condition on the right-hand side (++i < n) is never evaluated.


Conditional ternary operator (?)

The conditional operator returning a value if the expression evaluates to true and a different one if it evaluates to false.


Example:
condition ? result1 : result2;

If condition is true, the entire expression evaluates to result1, and otherwise to result2.


Example:
20 == 2 ? 6 : 4//evaluates to 4, since 20 is not equal to 2
20 == 2 * 10 ? 6 : 4//evaluates to 6, since 2 * 10 is equal to 20
2 > 1 ? a : b//evaluates to a, since 2 is greater than 2
a > b ? a : b//evaluates to whichever is greater a or b

Example:

1#include <iostream>
2using namespace std;
3
4int main() {
5    int a = 2, b = 5, c;
6    c = (a < b) ? a : b;
7    
8    cout << c << endl;
9    
10    return 0;
11}

Comma operator (,)

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the right-most expression is considered.


Example:
x = (y = 5, y - 2);

In this example assigned the value 5 to y first, and then assigned y - 2 to variable x. So, at the end, variable x would contain the value 3 while variable y would contain value 5.


Bitwise operators (&, |, ^, ~, <<, >>)

Bitwise operators modify variables considering the bit patterns that represent the values they store.


Operatorasm equivalentDescription
&ANDBitwise AND
|ORBitwise inclusive OR
^XORBitwise exclusive OR
~NOTUnary complement (bit inversion)
<<SHLShift bits left
>>SHRShift bits right

Explicit type casting operator

Type casting operators allow to convert a value of a given type to another type. It exist several ways to convert a type to another in C++ but the simplest is to precede the new type enclosed in round parentheses.


Example:
inti;
floatf = 3.14159;
i = (int)f;

The data type of type floating-point with the value 3.14159 is converted to type int and all of the remainder is lost. The notation as follows is possible too.


Example:
i = int(f);

Both notation of casting types are valid in C++.


sizeof

This operator accepts one parameter, which can be either a type or a variable, and returns the size in bytes of that type or object.

Example:
x = sizeof(char);

Here, x is assigned the value 1, because char is a type with a size of one byte.

The value returned by sizeof is a compile-time constant, so it is always determined before program execution.


Operator precedence

A single expression may have multiple operators.

Example:
x = 5 + 5 % 2;

In this expression assigned 6 to variable x, because the operator % has a higher precedence as the operator + and it assigned 5 % 2 with remainder 1 and at last it assigned 5 + 1 to variable x. Parts of an expression can be enclosed in parenthesis to override this precedence order.

Example:
x = 5 + (5 % 2);//x = 6 (same as without parenthesis)
x = (5 + 5) % 2;//x = 0

Table of C++ operators from greatest to smallest priority:

LevelPrecedence groupOperatorDescriptionGrouping
1Scope::scope qualifierLeft-to-right
2Postfix (unary)++postfix incrementLeft-to-right
--postfix decrement
( )functional forms
[ ]subscript
.member access
->member access
3Prefix (unary)++prefix incrementRight-to-left
--prefix decrement
~bitwise NOT
!logical NOT
+unary prefix
-unary prefix
&reference
*dereference
newallocation
deletedeallocation
sizeofparameter pack
(type)C-style type-casting
4Pointer-to-member.*access pointerLeft-to-right
->*access pointer
5Arithmetic: scaling*multiplicationLeft-to-right
/division
%modulo
6Arithmetic: addition+additionLeft-to-right
-subtraction
7Bitwise shift<<shift leftLeft-to-right
>>shift right
8Relational<comparison operatorLeft-to-right
>
<=
>=
9Equality==equalityLeft-to-right
!=inequality
10AND&Bitwise ANDLeft-to-right
11Exclusive OR^Bitwise XORLeft-to-right
12Inclusive OR|Bitwise ORLeft-to-right
13Conjunction&&Logical ANDLeft-to-right
14Disjunction||Logical ORLeft-to-right
15Assignment-level expression=assignmentRight-to-left
*=compound assignment
/=
%=
+=
-=
>>=
<<=
&=
^=
|=
?:conditional operator
16Sequencing,comma separatorLeft-to-right