Operators in C++ languages
Operators are classified according to the number of operands into:
- Unary operators – act on one operand (eg ++, --).
- Binary operators – apply to two operands (eg +, -, *).
- Ternary operators – use three operands, such as the conditional operator (?:).
- Arithmetic operators like +, - and * are used for basic mathematical operations.
- Relational operators (==, !=, >, <) allow comparing values.
Operator characteristics
- Operators are actions that run over operands, giving a particular result.
- Expressions are arbitrarily complex compositions of operand and operator.
- Operators can be applied to one operand (unary operator) or to two operands (binary operators).
- There is also one operator with three operands, which is ? : (explained later).
Example:
int result = (a < b) ? a : b; // the ternary operator returns 10 because a is less than b
Aritmetics operators
Operator | Using | Description |
---|---|---|
+ | op1+op2 | addition of two numbers |
- | op1-op2 | subtraction two numbers |
* | op1*op2 | Multiple op1 width op2 |
/ | op1/op2 | Division two numbers |
% | op1%op2 | Calculates the rest of division of two numbers |
Solution:
int main()() {
std::cout << "Enter values for R1 and R2: ";
std::cin >> R1 >> R2; // User inputs R1 and R2
Re = R1 * R2 / (R1 + R2); // Calculated solution for the given equation
std::cout << "Solution: " << Re << std::endl;
}
The remainder of the division of two numbers: The "%" operator
Suppose we want to divide two integer values: 7 and 3.
If we write 7 / 3
, we get the result 2. This is an integer result because we divided two integer values.
If we want to get the remainder of the division, we would use the %
operator.
For example, 7 % 3 = 1
.
Example:
Input the time in seconds and display it as mm:ss
.
Example: Input the time in minutes and print as mm: ss
int main()() {
std::cout << "Enter time in seconds: ";
std::cin >> time; // User enters time in seconds
/* Let's assume the user enters 132 seconds. Since one minute has 60 seconds,
we can convert 2*60s to two minutes, and the remaining seconds will be 132-(2*60)=12s.
This can be calculated using the division and modulo operators, "/" and "%". */
minutes = time / 60; // minutes=132/60=2
seconds = time % 60; // seconds=132%60=12
std::cout << "Time: " << minutes << " : " << seconds << std::endl;
The data type for the result | Data type for values |
---|---|
long | None of the values is float or double (whole number artifacts), a At least one of the operators is long type |
int | None of the values is float or double (integer arithmetic). No operand is long. |
double | At least one value is double type |
float | At least one value is a float type. None is double type |
Unary operators "++", "-"
Relational and conditional operators
Operator | Using | Return true if |
---|---|---|
> | op1>op2 | op1 greater then op2 |
>= | op1 >= op2 | op2 greater then or equal to op1 |
< | op1 < op2 | op1 Less then op2 |
<= | op1 <= op2 | op1 less then or equal to op2 |
== | op1 == op2 | op1 equal to op2 |
!= | op1 != op2 | op1 different to op2 |
An example of relational operators
int main()() {
std::cout << "Enter the value for a: ";
std::cin >> a;
std::cout << "Enter the value for b: ";
std::cin >> b;
if (a > b) {
}
Operator | using | return true if |
---|---|---|
&& | op1 && op2 | both op1 and op2 are true. op2 is calculated only if necessary |
|| | op1 || op2 | either op1 or op2 are true or both. op2 is calculated only if necessary |
! | !op | op is false |
& | op1 & op2 | both op1 and op2 are true. Always calculate op1 and op2 |
| | op1 | op2 | either op1 or op2 are true or both. Always calculate op1 and op2. |
^ | op1 ^ op2 | if op1 and op2 are different, or if one has the value true, but not both |
Examples of logical operators
bool x = true;
bool y = false;
bool result = (x && y); // result is false because both expressions are not true
Example: For the set values of integer variables a, b, c, determine the values of logical expressions:
- a>b
- ! a > b && !(b<c)
- a !=0 || !(a>(b>c))
Solution:
The values of logical expressions in C++ are also of type bool
. A logical expression has the value true if the condition is satisfied (true), and false if the condition is not satisfied (false). This differs from C language, where logical values are represented as integers (1 for true and 0 for false). If we define three integers with values 4
, 7
, and 11
, the values of the logical expressions will be as follows:
1. Expression a > b
It gives the value false because 4
is not greater than 7
.
a > b
4 > 7
false
2. Expression !(a > b && !(b < c))
It gives the value true. When we substitute the values for a
, b
, and c
, we get:
!(4 > 7 && !(7 < 11))
= !((false) && (true))
= !(false)
= true
First, the operators >
and <
are processed because they have higher precedence than logical operators. Thus, 4 > 7
is false, and 7 < 11
is true. Then, the &&&
operator combines these values: false && true
gives false. Finally, the negation !
turns false
into true.
3. Expression a != 0 || !(a > (b > c))
It gives the value true. When we substitute the values for a
, b
, and c
, we get:
4 != 0 || !(4 > (7 > 11))
= true || !(4 > false)
= true || !(false)
= true || true
= true
Explanation:
4 != 0
is true, because4
is not equal to0
.- The expression
(7 > 11)
is false, because7
is not greater than11
. - Then,
4 > false
treatsfalse
as0
, so the result is4 > 0
, which gives true. - Finally, the negation
!
givesfalse
, but the operator||
combines it with the first part (true || false
), resulting in true.
Conclusion:
The order of execution of operators in C++ follows precedence, where comparison operators (>
, <
, !=
) are executed before logical operators such as &&&
and ||
. Just like in mathematics, parentheses are used to clearly define the order of execution.
using namespace std;
int main() {
bool e, f, g;
a = 4; // Assigning value to variable a
b = 7; // Assigning value to variable b
c = 11; // Assigning value to variable c
// Calculating logical expressions
e = a > b; // e is true if a is greater than b, otherwise false
f = !(a > b && !(b < c)); // Combination of AND and NOT operators
g = a != 0 || !(a > (b > c)); // Combination of OR and NOT operators
// Printing the values of expressions
cout << "e=" << e << endl;
cout << "f=" << f << endl;
cout << "g=" << g << endl;
}
Operators by bit
- operators to perform logical operations between pairs of bits on the same positions within their operands
- shift operators
- ~ It performs complementing (negating) the value of its operand by bit. Thus, it converts from state 0 to state 1 and vice versa
- & Logical "and" for bit operations.
- | Logic included "or" for bit operations.
- ^ Logic exclusively "or" for bit operations.
- << It moves the left operand for as many binary places as the right-hand value of the right operand
- >> Moving the left operand for as many binary places to the right is the value of the right operand. Moving to the right of the n position is equivalent to dividing the number with 2 ^ n
Examples for operators by bits
- 25 & 5 = 1 0000000000011001 &
0000000000000001
- 25 | 5 = 29 0000000000011001 |
0000000000011101
- 25 ^ 5 = 28 0000000000011001 ^
0000000000011100
- 25 << 2 = 100 0000000000011001 <<2 =
- 25 >> 3 = 3 0000000000011001 &
0000000000000011
Assignment operator
Operator | Using | Equivalent to: |
---|---|---|
+= | op1 += op2 | op1 = op1 + op2 |
-= | op1 -= op2 | op1 = op1 - op2 |
*= | op1 *= op2 | op1 = op1 * op2 |
/= | op1 /= op2 | op1 = op1 / op2 |
%= | op1 %= op2 | op1 = op1 % op2 |
&= | op1 &= op2 | op1 = op1 & op2 |
|= | op1 |= op2 | op1 = op1 | op2 |
^= | op1 ^= op2 | op1 = op1 ^ op2 |
For instance:
int N=28;
N=N<<3;
The starting number 28 will be transformed to number 224 and this value is assigned to the same memory N.
- 28 << 3 = 224 0000000000011100 <<2 =
Difference between relational and logical operators
- Relational operators perform a comparison between two values, and the result of the comparison is a logical value (true or false). For example, is the number a greater than b.
- Logical operators combine or negate logical values. They do not work directly on numeric values like relational operators, but on results that are already true or false.
int b = 20;
int c = 15;
// First we use relational operators to get boolean values
bool condition1= (a < b); // true because 10 is less than 20
bool condition2= (c == 15); // true because c is equal to 15
// We then use logical operators to combine the results
bool finalResult = condition1 && condition2; // true because both conditions are true
The other operators in C++
Conditional expression: ? :
For entered integers a and b, specify a greater number.
We reserve the memory for 3 data, and b and larger than the two will be placed in the new variable maxAB.
int a,b,maxAB;
The user then enters a and b from the console:
cin>>a>>b;
To assign a value of maxAB, two variants are possible:
maxAB = a; if a >= b or
maxAB = b, if a < b
If you put both variants, the first value of the maxAB would be, and later it would change to b and it would always be b.
It is first necessary to ask whether a> b, and if it is true then maxAB = a is executed, otherwise maxAB = b;
For this, the conditional expression is used:
maxAB=(a>b) ? a : b;
Finally, this value should be displayed:
cout<< "maxAB="<<maxAB<<endl;
SIZEOF operator
#include <iomanip>
using namespace std;
int main() {
int a;
char b;
short c;
long d;
long long e;
unsigned long int f;
cout << "\nEnter integer a: ";
cin >> a;
cout << "\nEnter integer b: ";
cin >> b;
cout << "\nEnter integer c: ";
cin >> c;
cout << "\nEnter integer d: ";
cin >> d;
cout << "\nEnter integer e: ";
cin >> e;
cout << "\nEnter integer f: ";
cin >> f;
cout << "\nSize of int is " << sizeof(int) << " bytes, and it is equal to the size of a=" << sizeof(a) << " bytes";
cout << "\nSize of char is " << sizeof(char) << " bytes, and it is equal to the size of b=" << sizeof(b) << " bytes";
cout << "\nSize of short is " << sizeof(short) << " bytes, and it is equal to the size of c=" << sizeof(c) << " bytes";
cout << "\nSize of long is " << sizeof(long) << " bytes, and it is equal to the size of d=" << sizeof(d) << " bytes";
cout << "\nSize of long long is " << sizeof(long long) << " bytes, and it is equal to the size of e=" << sizeof(e) << " bytes";
cout << "\nSize of unsigned long int is " << sizeof(unsigned long int) << " bytes, and it is equal to the size of f=" << sizeof(f) << " bytes";
return 0;
}
Comma operator ","
Other operators
Operator | Operator Description |
---|---|
[] | Indexing |
() | Function Call |
& | Address of variable |
. | Access member of class or structure |
-> | Access member of class or structure via pointer |
:: | Scope resolution (used to access static members of a class or to resolve names within a namespace) |
* | Dereferencing pointer |
.* | Access member of class or structure via pointer to member |
->* | Access member of class or structure via pointer to member using pointer to object |
sizeof | Returns size of an object or type in bytes |
typeid | Returns the type of an object at runtime |
dynamic_cast | Dynamic casting between classes within the same hierarchy |
static_cast | Compile-time casting without runtime check |
const_cast | Removes or adds `const` qualifier to a type |
reinterpret_cast | Reinterprets the bits of an object for casting between unrelated types |
Operator Priority Table
The table below describes the order of priorities and association of operators in C / C ++. The advantage of the operator decreases from top to bottom.
Priority | Number of Operands | Grouping Direction: | Operators: |
---|---|---|---|
15 | 1 or 2 | left | [] () . -> |
14 | 1 | right | ++ -- ~ ! + - * & sizeof typeid new delete |
13 | 2 | left | * / % |
12 | 2 | left | + - |
11 | 2 | left | << >> |
10 | 2 | left | < <= > >= |
9 | 2 | left | == != |
8 | 2 | left | & |
7 | 2 | left | ^ |
6 | 2 | left | | |
5 | 2 | left | && |
4 | 2 | left | || |
3 | 2 | right | ?: |
2 | 2 | right | = += -= *= /= %= &= ^= |= <<= >>= |
1 | 2 | left | , |
Suggested Content for "Adding Additional Explanations"
Operator Overloading in C++
Example:
using namespace std;
class Complex {
public:
// Overloading the + operator to add two Complex numbers
Complex operator+(const Complex& other) {
// Displaying the complex number in the form "real + imag i"
void display() {
int main() {
Complex c1(1.2, 2.3), c2(3.4, 4.5);
// Adding two Complex numbers using the overloaded + operator
Complex c3 = c1 + c2;
// Displaying the result
c3.display();
return 0;
Prefix vs. Postfix Unary Operators
- Prefix (++x): Increments the value first and then evaluates it.
- Postfix (x++): Evaluates the current value first and then increments it.
Example
using namespace std;
int main() {
int x = 5;
// Demonstrate prefix increment: ++x increments x first and then returns the value
cout << "Prefix: " << ++x << endl; // Output: 6
// Reset the value of x back to 5 for the next demonstration
x = 5;
// Demonstrate postfix increment: x++ returns the value first and then increments x
cout << "Postfix: " << x++ << endl; // Output: 5 (x becomes 6 after this line)
return 0;
- Prefiks (++x): Kada se koristi prefiksni inkrement, vrednost promenljive se prvo poveća za 1, a zatim se koristi u izrazu. U ovom primeru, kada je
x
inicijalizovano sa 5,++x
prvo povećavax
na 6 i zatim štampa tu novu vrednost. Rezultat je6
. - Postfiks (x++): Kada se koristi postfiksni inkrement, trenutna vrednost promenljive se koristi u izrazu, a zatim se promenljiva povećava za 1. U ovom primeru,
x
je inicijalizovano sa 5,x++
štampa trenutnu vrednost (5), a tek nakon toga povećavax
na 6.
Razlika između ova dva operatora je važna u složenijim izrazima i algoritmima, gde redosled operacija može uticati na rezultat.
Implementation in the class
class Counter {
int value;
// Public constructor with default value (0)
public:
Counter (int v = 0) : value(v) {}
// Prefix increment operator overload
Counter& operator++() {
++value;
return *this;
// Postfix increment operator overload
Counter operator++(int) {
Counter temp = *this;
// Increment the value after saving the current state
++value;
return temp;
// Display the current value of the counter
void display() const {
Klasa Counter
: Ova klasa predstavlja brojač koji čuva vrednost i omogućava povećanje te vrednosti pomoću operatora inkrementa. Klasa sadrži privatnu promenljivu value
koja predstavlja trenutnu vrednost brojača.
- Konstruktor: Konstruktor klase
Counter
prima argumentv
(podrazumevana vrednost je 0) koji inicijalizuje vrednost brojača. - Prefix inkrement (
++x
): U preklopljenoj verziji prefix inkrementa (operator++()
), vrednostvalue
se prvo povećava, a zatim se vraća referenca na trenutni objekat (*this
). - Postfix inkrement (
x++
): U preklopljenoj verziji postfix inkrementa (operator++(int)
), prvo se čuva trenutni objekat (da bi mogao biti vraćen), zatim se vrednost povećava, i na kraju se vraća kopija objekta pre inkrementa. - Metod
display
: Ovaj metod jednostavno štampa trenutnu vrednost brojača koristećicout
.
Napomena: Razlika između prefix i postfix inkrementa je u tome što prefix inkrement vraća ažurirani objekat odmah, dok postfix inkrement vraća objekat pre nego što je inkrementiran (pre povećanja vrednosti).
Previous
|< Data in C++ language |
Next
Selection statements >| |