Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C++

Learn step by step



Operators

Operators of C++ are similar to Operators of C language. They are the symbol which operates on value or a variable. For example: + is a operator to perform addition.


Assignment operator (=)

Assignment Operator is for assigning a value to the variable. Following assignment operators supported by C++ language:

a = 7;

This statement assigns the integer value 7 to the variable a. The assignment operation always takes place from right to left:

a = b;

This statement assigns to variable a the value contained in variable b. The value of a at the moment this statement is executed is lost and replaced by the value of b.

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

For example, let us have a look at the following code - I have included the evolution of the content stored in the variables as comments:


// assignment operator
#include <iostream>
using namespace std;

int main ()
{
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

cout << "a:";
cout << a;
cout << " b:";
cout << b;
}

Output

a:4 b:7

Compound Assignment Operators

Besides usual simple assignment operator '=', C++ also provides the so-called compound assignment operators:


Operator Usage Description Example
= var = expr Assign the value of the LHS to the variable at the RHS x = 5;
+= var += expr same as var = var + expr x += 5; same as x = x + 5
-= var -= expr same as var = var - expr x -= 5; same as x = x - 5
*= var *= expr same as var = var * expr x *= 5; same as x = x * 5
/= var /= expr same as var = var / expr x /= 5; same as x = x / 5
%= var %= expr same as var = var % expr x %= 5; same as x = x % 5

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

C++ has following arithmetic operators for numbers: short, int, long, long long, char (treated as 8-bit signed integer), unsigned short, unsigned int, unsigned long, unsigned long long, unsigned char, float, double and long double.


Operator Description Usage Examples
* Multiplication expr1 * expr2 2 * 3 → 6; 3.3 * 1.0 → 3.3
/ Division expr1 / expr2 1 / 2 → 0; 1.0 / 2.0 → 0.5
% Remainder (Modulus) expr1 % expr2 5 % 2 → 1; -5 % 2 → -1
+ Addition expr1 + expr2 1 + 2 → 3; 1.1 + 2.2 → 3.3
- Subtraction expr1 - expr2 1 - 2 → -1; 1.1 - 2.2 → -1.1

All above operators are binary operators, i.e., they take 2 operands. The multiplication, division & remainder take precedence over addition and subtraction. Within the same precedence level (e.g., addition and subtraction), the expression is evaluated from left to right. For example, 1+2+3-4 is evaluated as ((1+2)+3)-4.

It is important to take note that int/int produces an int, with the result truncated, e.g., 1/2 → 0 (instead of 0.5).


Increment/Decrement Operators

C++ supports unary arithmetic operators: increment '++' and decrement '--'.


Operator Example Result
++ x++; ++x Increment by 1, same as x += 1
-- x--; --x Decrement by 1, same as x -= 1

/* Test on increment (++) and decrement (--) Operator (TestIncDec.cpp) */
#include <iostream>
using namespace std;

int main() {
int mark = 76; // declare & assign
cout << mark << endl; // 76

mark++; // increase by 1 (post-increment)
cout << mark << endl; // 77

++mark; // increase by 1 (pre-increment)
cout << mark << endl; // 78

mark = mark + 1; // also increase by 1 (or mark += 1)
cout << mark << endl; // 79

mark--; // decrease by 1 (post-decrement)
cout << mark << endl; // 78

--mark; // decrease by 1 (pre-decrement)
cout << mark << endl; // 77

mark = mark - 1; // also decrease by 1 (or mark -= 1)
cout << mark << endl; // 76
return 0;
}

The increment/decrement operator can be placed before the operand (prefix operator), or after the operand (postfix operator). This has different meaning in operations.


Operator Description Example Result
++var Pre-Increment
Increment var, then use the new value of var
y = ++x; same as x=x+1; y=x;
var++ Post-Increment
Use the old value of var, then increment var
y = x++; same as oldX=x; x=x+1; y=oldX;
--var Pre-Decrement y = --x; same as x=x-1; y=x;
var-- Post-Decrement y = x--; same as oldX=x; x=x-1; y=oldX;

If '++' or '--' involves in an another operation, then pre-order or post-order is important to specify the order of execution.

x = 5;
cout << x++ << endl; // Save x(5); Increment x(=6); Print old x(5).
x = 5;
cout << ++x << endl; // Increment x(=6); Print x(6).
// This is confusing! So try to avoid it! What is i=++i? What is i=i++?

Prefix operator (e.g, ++i) could be more efficient than postfix operator (e.g., i++).


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

2 expressions can be compared using relational and Comparison operators. E.g., to know if 2 values are equal or if one is greater than other.

The result of such operation is either true or false (i.e., Boolean value).

C++ has 6 comparison operators (relational operators):


Operator Description Usage Example (x=5, y=8)
== Equal to expr1 == expr2 (x == y) → false
!= Not Equal to expr1 != expr2 (x != y) → true
> Greater than expr1 > expr2 (x > y) → false
>= Greater than or equal to expr1 >= expr2 (x >= 5) → true
< Less than expr1 < expr2 (y < 8) → false
<= Less than or equal to expr1 >= expr2 (y <= 8) → true

In C++, these operations returns a bool value of either false (0) or true (1 or a non-zero value).

Each comparison operation involves 2 operands, e.g., x <= 100. It is invalid to write 1 < x < 100 in programming. Instead, we need to break out the two comparison operations x > 1, x < 100, and join with with a logical AND operator, i.e., (x > 1) && (x < 100), where && denotes AND operator.

C++ provides four logical operators (which operate on boolean operands only):


Operator Description Usage
&& Logical AND expr1 && expr2
|| Logical OR expr1 || expr2
! Logical NOT !expr
^ Logical XOR expr1 ^ expr2

The truth tables are as follows:


AND (&&) true false
true true false
false false false


OR (||) true false
true true true
false true false


NOT (!) true false
false true


XOR (^) true false
true false true
false true false

Conditional ternary operator ( ? )

It is an abbreviation of If else condition. If condition is true, then true block is evaluated, otherwise false block is evaluated.
Syntax:

condition ? true_block : false block;
6==5 ? 4 : 3 // it evaluates 3, because 6 is not equal to 5.
6==5+1 ? 4 : 3 // it evaluates 4, because 6 is equal to 5+1(i.e.,6).
4>3 ? a : b // it evaluates to the value of a, since 4 is greater than 3.
a>b ? a : b // it evaluates to whichever is greater.

// conditional operator
#include <iostream>
using namespace std;

int main ()
{
int a,b,c;

a=2;
b=7;
c = (a>b) ? a : b;

cout << c << '\n';
}

Output

7

In above example, a is equal to 2, and b is equal to 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value which was b (with a value of 7).


Comma operator ( , )

Comma operator is used to distinct 2 or more expressions/values that are included where only one is expected.

E.g.:

int a,b;


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

These operators modify the bit patterns that represent the values of variables.

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


sizeof

This accepts one parameter, it can be either a type or a variable, & returns size of that type or object in bytes:

s = sizeof (char);

Here, variable s is assigned the value 1, since char is a type with a size of one byte.


Precedence of operators

Operator precedence defines order of operator evolution. Operator precedence determines the grouping of terms in an expression. This affects in which order an expression is evaluated. Operators having higher precedence than others is evaluated firstly; for example, the multiplication operator has higher precedence than the addition operator so multiplication take place before addition.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom. In any expression, higher precedence operators will be evaluated first then lower.


LevelPrecedence groupOperatorDescriptionGrouping
1Scope::scope qualifierLeft-to-right
2Postfix (unary)++ --postfix increment / decrementLeft-to-right
()functional forms
[]subscript
. ->member access
3Prefix (unary)++ --prefix increment / decrementRight-to-left
~ !bitwise NOT / logical NOT
+ -unary prefix
& *reference / dereference
new deleteallocation / deallocation
sizeofparameter pack
(type)C-style type-casting
4Pointer-to-member.* ->*access pointerLeft-to-right
5Arithmetic: scaling* / %multiply, divide, moduloLeft-to-right
6Arithmetic: addition+ -addition, subtractionLeft-to-right
7Bitwise shift<< >>shift left, shift rightLeft-to-right
8Relational< > <= >=comparison operatorsLeft-to-right
9Equality== !=equality / inequalityLeft-to-right
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 expressions= *= /= %= += -=
>>= <<= &= ^= |=
assignment / compound assignmentRight-to-left
?:conditional operator
16Sequencing,comma separatorLeft-to-right

When an single expression contains 2 operators with same precedence level, grouping determines which one is evaluated firstly: either left-to-right or right-to-left.

Enclosing all sub-statements in parentheses (even those unnecessary because of their precedence) improves code readability.



Related Videos