Once we know of the existence of variables and constants we can begin to operate with them. For that purpose, C++ provides the operators, which in this language are a set of keywords and signs that are not part of the alphabet but are available in all keyboards. It is important to know them since they are the basis of the C++ language.
You do not have to memorize all the content of this page, the details are only provided to serve as a later reference in case you need it.
Assignation operator in C++
The assignation operator serves to assign a value to a variable.
1 2 3 |
a = 5; |
assigns the integer value 5 to variable a. The part at the left of the = operator is known as lvalue (left value) and the right one as rvalue (right value). lvalue must always be a variable whereas the right side can be either a constant, a variable, the result of an operation or any combination of them.It is necessary to emphasize that the assignation operation always takes place from right to left and never at the inverse.
1 2 3 |
a=b; |
assigns to variable a (lvalue) the value that contains variable b (rvalue) independently of the value that was stored in a at that moment. Consider also that we are only assigning the value of b to a and that a later change of b would not affect the new value of a.For example, if we take this code (with the evolution of the variables’ content in green color):
1 2 3 4 5 6 7 |
int a, b; // a:? b:? a = 10; // a:10 b:? b = 4; // a:10 b:4 a = b; // a:4 b:4 b = 7; // a:4 b:7 |
will give us the result that the value contained in a is 4 and the one contained in b is 7. The final modification of b has not affected a, although before we have declared a = b; (right-to-left rule).A property that C++ has over other programming languages is that the assignation operation can be used as the rvalue (or part of an rvalue) for another assignation. For example:
1 2 3 |
a = 2 + (b = 5); |
is equivalent to:
1 2 3 4 |
b = 5; a = 2 + b; |
that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous assignation of b (that is 5), leaving a with a final value of 7. Thus, the following expression is also valid in C++:
1 2 3 |
a = b = c = 5; |
assigns 5 to the three variables a, b and c.
Arithmetic operators in C++
The five arithmetical operations supported by the language are:
+ | addition |
– | subtraction |
* | multiplication |
/ | division |
% | module |
Operations of addition, subtraction, multiplication and division should not suppose an understanding challenge for you since they literally correspond with their respective mathematical operators.The only one that may not be known by you is the module, specified with the percentage sign (%). Module is the operation that gives the remainder of a division of two integer values. For example, if we write a = 11 % 3;, the variable a will contain 2 as the result since 2 is the remainder from dividing 11 between 3.
For Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> using namespace std; int main() { int x = 25; int y = 13; //*** Addition *** cout << "Total of x + y = " << (x + y) << endl; //*** Subtraction *** cout << "Subtraction of x - y = " << (x - y) << endl; //*** Multiplication *** double a = 255.75; double b = 3; cout << "Multiplication of a * b = " << (a * b) << endl; //*** Division *** cout << "Division of a / b = " << (a / b) << endl; return 0; } |
Compound assignation operators in C++
A feature of assignation in C++ that contributes to its fame of sparing language when writing are the compound assignation operators (+=, -=, *= and /= among others), which allow to modify the value of a variable with one of the basic operators:
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a - 5;
a /= b; is equivalent to a = a / b;
price *= units + 1; is equivalent to price = price * (units + 1);
and the same for all other operations.
Increase and decrease in C++
Another example of saving language when writing code are the increase operator (++) and the decrease operator (--). They increase or reduce by 1 the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:
1 2 3 4 5 |
a++; a+=1; a=a+1; |
A characteristic of this operator is that it can be used both as a prefix or as a suffix. That means it can be written before the variable identifier (++a) or after (a++). Although in simple expressions like a++ or ++a they have exactly the same meaning, in other operations in which the result of the increase or decrease operation is evaluated as another expression they may have an important difference in their meaning: In case that the increase operator is used as a prefix (++a) the value is increased before the expression is evaluated and therefore the increased value is considered in the expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the expression. Notice the difference
For Example:
1 2 3 4 5 |
B=3; A=++B; // A is 4, B is 4 |
1 2 3 4 5 |
B=3; A=B++; // A is 3, B is 4 |
In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and B is later increased
Relational operators in C++
In order to evaluate a comparison between two expressions we can use the Relational operators. As specified by the ANSI-C++ standard, the result of a relational operation is a bool value that can only be true or false, according to the result of the comparison.
We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other. Here is a list of the relational operators that can be performed in C++:
== | Equal |
!= | Different |
> | Greater than |
< | Less than |
>= | Greater or equal than |
<= | Less or equal than |
Here you have some examples
(7 == 5) | would return false. |
(5 > 4) | would return true. |
(3 != 2) | would return true. |
(6 >= 6) | would return true. |
(5 < 5) | would return false. |
For Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <iostream> using namespace std; main() { int a = 21; int b = 10; int c ; if( a == b ) { cout << "Line 1 - a is equal to b" << endl ; } else { cout << "Line 1 - a is not equal to b" << endl ; } if( a < b ) { cout << "Line 2 - a is less than b" << endl ; } else { cout << "Line 2 - a is not less than b" << endl ; } if( a > b ) { cout << "Line 3 - a is greater than b" << endl ; } else { cout << "Line 3 - a is not greater than b" << endl ; } /* Let's change the values of a and b */ a = 5; b = 20; if( a <= b ) { cout << "Line 4 - a is either less than \ or equal to b" << endl ; } if( b >= a ) { cout << "Line 5 - b is either greater than \ or equal to b" << endl ; } return 0; } |
Logic operators in C++
Operator ! is equivalent to boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to invert the value of it, producing false if its operand is true and true if its operand is false. It is like saying that it returns the opposite result of evaluating its operand. For example
!(5 == 5) | returns false because the expression at its right (5 == 5) would be true. |
!(6 <= 4) | returns true because (6 <= 4) would be false. |
!true | returns false. |
!false | returns true. |
Logic operators && and || are used when evaluating two expressions to obtain a single result. They correspond with boolean logic operations AND and OR respectively. The result of them depends on the relation between its two operands
First Operand a |
Second Operand b |
result a && b |
result a || b |
true | true | true | true |
true | false | false | true |
false | true | false | true |
false | false | false | false |
For example
( (5 == 5) && (3 > 6) ) returns false ( true && false ).
( (5 == 5) || (3 > 6)) returns true ( true || false )
Conditional operator in C++
The conditional operator evaluates an expression and returns a different value according to the evaluated expression, depending on whether it is true or false. Its format is:
1 2 3 |
condition ? result1 : result2 |
- if condition is true the expression will return result1, if not it will return result2
-
1234567==5 ? 4 : 3 //returns 3 since 7 is not equal to 5.7==5+2 ? 4 : 3 //returns 4 since 7 is equal to 5+2.5>3 ? a : b // returns a, since 5 is greater than 3.a>b ? a : b // returns the greater one, a or b.
-
Bitwise Operators in C++
Bitwise operators modify variables considering the bits that represent the values that they store, that means, their binary representation
op asm Description & AND Logical AND | OR Logical OR ^ XOR Logical exclusive OR ~ NOT Complement to one (bit inversion) << SHL Shift Left >> SHR Shift Right -
Explicit type casting operators in C++
Type casting operators allows you to convert a datum of a given type to another. There are several ways to do this in C++, the most popular one, compatible with the C language is to precede the expression to be converted by the new type enclosed between parenthesis ():
1 2 3 4 5 |
int i; float f = 3.14; i = (int) f; |
The previous code converts the float number 3.14 to an integer value (3). Here, the type casting operator was (int). Another way to do the same thing in C++ is using the constructor form: preceding the expression to be converted by the type and enclosing the expression between parenthesis
1 2 3 |
i = int ( f ); |
-
sizeof()
- This operator accepts one parameter, that can be either a variable type or a variable itself and returns the size in bytes of that type or object:
-
123a = sizeof (char);
- This will return 1 to a because char is a one byte long type.
The value returned by sizeof is a constant, so it is always determined before program execution. -
Other operators
- Later in the tutorial we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming. Each one is treated in its respective section.
Priority of operators
When making complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression:
1 2 3 |
a = 5 + 7 % 2 |
we may doubt if it really means:
1 2 3 4 |
a = 5 + (7 % 2) //with result 6, a = (5 + 7) % 2 //with result 0 |
The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference we may already know from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows:
Priority | Operator | Description | Associativity |
1 | :: | scope | Left |
2 | () [ ] -> . sizeof | Left | |
3 | ++ -- | increment/decrement | Right |
~ | Complement to one (bitwise) | ||
! | unary NOT | ||
& * | Reference and Dereference (pointers) | ||
(type) | Type casting | ||
+ - | Unary less sign | ||
4 | * / % | arithmetical operations | Left |
5 | + - | arithmetical operations | Left |
6 | << >> | bit shifting (bitwise) | Left |
7 | < <= > >= | Relational operators | Left |
8 | == != | Relational operators | Left |
9 | & ^ | | Bitwise operators | Left |
10 | && || | Logic operators | Left |
11 | ?: | Conditional | Right |
12 | = += -= *= /= %= >>= <<= &= ^= |= |
Assignation | Right |
13 | , | Comma, Separator | Left |
Associativity defines -in the case that there are several operators of the same priority level- which one must be evaluated first, the rightmost one or the leftmost one.
All these precedence levels for operators can be manipulated or become more legible using parenthesis signs ( and ), as in this example:
1 2 3 |
a = 5 + 7 % 2; |
might be written as:
1 2 3 4 |
a = 5 + (7 % 2); a = (5 + 7) % 2; |
according to the operation that we wanted to perform.
Source: