Operators In C++
Topic asked in December 2022 (CBCS) and July 2022 (CBCS) question paper.
Operators are symbols that perform specific mathematical or logical operations on operands.
Consider the expression 2 + 3 = 5, here 2 and 3 are operands and +
is called operator.
Types Of Operators
- Unary operator
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operator
- Ternary or Conditional Operator
Unary Operators
Unary operators are operators which are used to calculate the result on only one operand. Unary operators are used on a single operand in order to calculate the new value of that variable. Unary operators can be used either in the prefix position or the postfix position of the operand.
Types of Unary Operators
-
Unary Plus (+) - This Unary Operator is denoted by the
+
sign and it does not make any difference to the value of the operand. It is just used to denote that the operand is of a positive value.Output:-
-
Unary Minus (-) - The
-
sign is used in this Unary Operator type and its main function is that it changes the sign value of the operand. It has the function of converting a positive value to a negative value and vice versa.Output:-
-
sizeof() - sizeof Unary Operator is used to return the size of the operand, in bytes. For example, in C++, the int data type is of the size 4 bytes. This value will be returned by the sizeof operator. The sizeof() operator is used as a function in the program.
Output:-
-
Addressof Operator (&) - In this type, the operator returns the address of the variable stored in the memory location. It returns the address value of the memory location where the variable is stored.
Output:-
-
Indirection Operator (*) - This type of operator returns the value stored in the memory location by pointing it to the memory location of the variable.
Output:-
Unary Increment (++)
Topic asked in February 2022 (CBCS) question paper.
Increment Operator is used to increase the value of the operand by 1. They are used only with Integer Variables and Operands having Numerical values. They cannot be used with a Variable containing the values of a Character or String.
They can be used in both the Prefix and the Postfix position of the operand. The Position used by the Increment Operator in the program statement decides how the operator will function.
If the Increment Operators are being used in the Prefix position, then, the Increment function will be done before the evaluation of the expression. If the Increment Operators are being used in the Postfix position, then, the Increment function will be done after the evaluation of the expression.
Example:-
Output:-
Explanation:- In our First cout statement, the Pre-Increment Operator is used. Thus, the value of x is incremented by 1 i.e., x = x + 1 = 10 + 1 = 11
Then we assign value to the variable a in the expression a = x++. Here, Post-Increment Operator is used.
This means that First the value of x will be assigned to a and then x will be incremented by 1. Hence the Output a = 11, new value of x = 12
Unary Decrement (--)
Topic asked in February 2022 (CBCS) question paper.
The main function of the Decrement Operator is to decrease the numerical count of the variable by a value of 1. They are also used only with Integer Variables and Operands having Numerical values and cannot be used with a Variable containing the values of a Character or String.
They are also used in both the Prefix and the Postfix position of the operand. The Position used by the Decrement Operator in the program statement decides how the operator will function.
If the Decrement Operator is being used in the Prefix position, then, the Decrement function will be done before the the evaluation of the expression. If the Decrement Operator is being used in the Postfix position, then, the Decrement function will be done after the evaluation of the expression.
Example:-
Output:-
Explanation:- In our First cout statement, the Pre-Decrement Operator is used. Thus, the value of x will be decremented by 1 i.e., x = x - 1 = 10 - 1 = 9
Then we assign value to the variable a in the expression a = x--. Here, Post-Decrement Operator is used.
This means that First the value of x will be assigned to a and then x will be decremented by 1. Hence the Output a = 9, new value of x = 8
The Postfix Operator position has a higher precedence level than the Prefix Operator position. Postfix Operators are evaluated from left-to-right associativity and the Prefix Operators are evaluated from right-to-left associativity.
Arithmetic Operators
Topic asked in July 2022 (CBCS) question paper.
In C++, Arithmetic Operators are symbols used to perform common arithmetic operations like addition, subtraction, multiplication, division, modulus, etc. They are used within the equation to perform a number of basic mathematical calculations.
Types Of Arithmetic Operators
Arithmetic Operators use two operands and an operator between them in order to calculate the result
Operator | Operation |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo Operation (Remainder After Division) |
Arithmetic Operator example:-
Output:-
Note: The %
operator can only be used with integers.
Relational Operators
These operators are used for the comparison of the values of two operands. For example, '>' checks if one operand is greater than the other operand or not, etc. The result returns a Boolean value, i.e., true or false.
Types Of Relational Operators
Operator | Meaning | Example |
---|---|---|
== | Is Equal To | 7 == 9 gives us false |
!= | Not Equal To | 7 != 9 gives us true |
> | Greater Than | 7 > 9 gives us false |
< | Less Than | 7 < 9 gives us true |
>= | Greater Than or Equal To | 7 >= 9 gives us false |
<= | Less Than or Equal To | 7 <= 9 gives us true |
Relational Operator example:-
Output:-
Note: Relational operators are used in decision-making and loops.
Logical Operators
Topic asked in July 2022 (CBCS) question paper.
Logical operators are used to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.
Types Of Logical Operators
Operator | Meaning | Example |
---|---|---|
&& | Logical AND. True only if all operands are true. | expression1 && expression2 |
|| | Logical OR. True if at least one operand is true. | expression1 || expression2 |
! | Logical NOT. True only if the operand is false. | !expression |
Logical Operator example:-
Output:-
Explanation:-
Logical AND (&&)
- (7 != 9) && (7 < 9) evaluates to 1 because both operands (7 != 9) and (7 < 9) are 1 (true).
- (7 == 9) && (7 < 9) evaluates to 0 because the operand (7 == 9) is 0 (false).
- (7 == 9) && (7 > 9) evaluates to 0 because both operands (7 == 9) and (7 > 9) are 0 (false).
Logical OR (||)
- (7 != 9) || (7 < 9) evaluates to 1 because both operands (7 != 9) and (7 < 9) are 1 (true).
- (7 != 9) || (7 > 9) evaluates to 1 because the operand (7 != 9) is 1 (true).
- (7 == 9) || (7 > 9) evaluates to 0 because both operands (7 == 9) and (7 > 9) are 0 (false).
Logical NOT (!)
- !(9 == 2) evaluates to 1 because the operand (9 == 2) is 0 (false).
- !(9 == 9) evaluates to 0 because the operand (9 == 9) is 1 (true).
Assignment Operator
In C++, assignment operators are used to assign values to variables.
Types Of Assignment Operators
Operator | Example | Equivalent to |
---|---|---|
= | a = b | a = b |
+= | a += b | a = a + b |
-= | a -= b | a = a - b |
*= | a *= b | a = a * b |
/= | a /= b | a = a / b |
%= | a %= b | a = a % b |
Simple Assignment Operator
Here, =
is also called Simple-assignment operator and
assigns its right operand to its left operand. In easy terms, this operator is used to assign the value on the right to the variable on the left.
Example:-
Output:-
Shorthand Assignment Operator
Here, +=
, -=
, *=
, /=
, %=
are also called Shorthand Assignment Operators
and they combines one of the arithmetic or bitwise operators with the assignment operator. They are also called as compound assignment operators.
A Shorthand Assignment Operator is a shorter way of expressing something that is already available in the programming statements.
Example:-
Output:-
Assignment Statement
An Assignment statement is a statement that is used to set a value to the variable name in a program.
The symbol used in an assignment statement is =
and is called assignment operator.
Note: The Assignment Operator =
should not be confused with ==
which
is relational operator and is used for equality purpose.
The Basic Syntax of Assignment Statement in C++ is :
variable = expression;
where,
- variable = variable name
- expression = it could be either a direct value or a math expression/formula or a function call
For example:-
In the above-given example, Variable 'a' is assigned a value in the same statement as per its defined data type. A data type is only declared for Variable 'b'. The 3rd line of code assigns the value for Variable 'b'.
Assignment Statement Forms
-
Basic Form - This is one of the most common forms of Assignment Statements. Here the Variable name is defined, initialized, and assigned a value in the same statement. This form is generally used when we want to use the Variable quite a few times and we do not want to change its value very frequently.
-
Tuple Assignment - Generally, we use this form when we want to define and assign values for more than 1 variable at the same time. This saves time and is an easy method. Note that here every individual variable has a different value assigned to it.
-
Sequence Assignment or Chain Assignment - In this format, a single value is assigned to two or more variables.
-
Augmented Assignment - In this format, we use the combination of mathematical expressions and values for the Variable. Other augmented Assignment forms are: &=, -=, **=, etc.
Bitwise Operators
In C++, bitwise operators are used to perform operations on individual bits. The operators are first converted to bit-level and then the calculation is performed on the operands.
Types Of Bitwise Operators
Operator | Name |
---|---|
& | Bitwise AND Operator |
| | Bitwise OR Operator |
^ | Bitwise XOR Operator |
~ | Bitwise Complement Operator |
<< | Bitwise Left Shift Operator |
>> | Bitwise Right Shift Operator |
1. Bitwise AND Operator - The bitwise AND &
operator returns 1 if and only if both the operands are 1. Otherwise, it returns 0.
The following table demonstrates the working of the bitwise AND operator. Let a and b be two operands that can only take binary values i.e. 1 and 0.
a | b | a & b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
Let's take a look at the bitwise AND operation of two integers 12 and 25:
Example Program:-
Output:-
2. Bitwise OR Operator - The bitwise OR |
operator returns 1 if at least one of the operands is 1. Otherwise, it returns 0.
The following truth table demonstrates the working of the bitwise OR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.
a | b | a | b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
Let us look at the bitwise OR operation of two integers 12 and 25:
Example Program:-
Output:-
3. Bitwise XOR Operator - The bitwise XOR ^
operator returns 1 if and only if one of the operands is 1.
However, if both the operands are 0, or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR operator. Let a and b be two operands that can only take binary values i.e. 1 or 0.
a | b | a ^ b |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Let us look at the bitwise XOR operation of two integers 12 and 25:
Example Program:-
Output:-
4. Bitwise Complement Operator - The bitwise complement operator is a unary operator (works on only one operand).
It is denoted by ~
that changes binary digits 1 to 0 and 0 to 1.
![Bitwise Complement](https://res.cloudinary.com/hptuexamhelper/image/upload/f_auto,q_auto/cpp-bitwise-complement_rryjys.webp)
It is important to note that the bitwise complement of any integer N is equal to -(N + 1). For example,
Consider an integer 35. As per the rule, the bitwise complement of 35 should be -(35 + 1) = -36. Now, let's see if we get the correct answer or not.
In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we convert the result into decimal we get 220.
However, it is important to note that we cannot directly convert the result into decimal and get the desired output. This is because the binary result 11011100 is also equivalent to -36.
To understand this we first need to calculate the binary output of -36. We use 2's complement to calculate the binary of negative integers.
2's Complement
The 2's complement of a number N gives -N.
In binary arithmetic, 1's complement changes 0 to 1 and 1 to 0.
And, if we add 1 to the result of the 1's complement, we get the 2's complement of the original number.
For example,
Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the bitwise complement of 35 that we have calculated in the previous section.
Hence, we can say that the bitwise complement of 35 = -36.
Example Program:-
Output:-
In the above example, we declared two integer variables num1 and num2, and initialized them with the values of 35 and -150 respectively.
We then computed their bitwise complement with the codes (~num1) and (~num2) respectively and displayed them on the screen.
This is exactly what we got in the output.
5. C++ Right Shift Operator - The right shift operator shifts all bits towards the right by a certain number of specified bits. It is denoted by >>.
When we shift any number to the right, the least significant bits are discarded, while the most significant bits are replaced by zeroes.
![Right Shift](https://res.cloudinary.com/hptuexamhelper/image/upload/f_auto,q_auto/Right-shift_z3z9nf.webp)
As we can see from the image above, we have a 4-bit number. When we perform a one-bit right shift operation on it, each individual bit is shifted to the right by 1 bit.
As a result, the right-most bit is discarded, while the left-most bit remains vacant. This vacancy is replaced by a 0.
6. C++ Left Shift Operator - The left shift operator shifts all bits towards the left by a certain number of specified bits. It is denoted by <<
.
![Left Shift](https://res.cloudinary.com/hptuexamhelper/image/upload/f_auto,q_auto/left-shift_ofba5n.webp)
As we can see from the image above, we have a 4-bit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.
As a result, the left-most bit is discarded, while the right-most bit remains vacant. This vacancy is replaced by a 0.
Example Program:-
Output:-
From the output of the program above, we can infer that, for any number N, the results of the shift right operator are:
Similarly, the results of the shift left operator are:
Hence we can conclude that,
Ternary or Conditional Operators
The conditional operator (also known as the ternary operator) in C++ is a shorthand way of writing an if-else
statement.
It allows you to evaluate a condition and return one value if the condition is true and another value if the condition is false.
The syntax of the conditional operator is:-
The ternary operator ? determines the answer on the basis of the evaluation of condition. If it is true, then Expression 1 gets evaluated and is used as the answer for the expression. If condition is false, then Expression 2 gets evaluated and is used as the answer for the expression.
This operator takes three operands, therefore it is known as a Ternary Operator.
Ternary Operator Example
Output:-
Precedence of Operators
The precedence of operators in C++ determines the order in which operators are evaluated within an expression. Operators with higher precedence are evaluated before operators with lower precedence. If operators have the same precedence, the associativity of the operators comes into play, determining the order of evaluation.
Here, higher the category in table higher the precedence.
Category | Operator | Associativity |
---|---|---|
Postfix | () [] . -> | Left to Right |
Unary | ++ -- + - ! ~ * & sizeof | Right to Left |
Multiplicative | * / % | Left to Right |
Additive | + - | Left to Right |
Shift | << >> | Left to Right |
Relational | < <= > >= | Left to Right |
Equality | == != | Left to Right |
Bitwise AND | & | Left to Right |
Bitwise XOR | ^ | Left to Right |
Bitwise OR | | | Left to Right |
Logical AND | && | Left to Right |
Logical OR | || | Left to Right |
Conditional | ? : | Right to Left |
Assignment | = += -= *= /= %= &= ^= |= <<= >>= | Right to Left |
Comma | , | Left to Right |
Examples:-
Example Program 1
Output:-
Explanation: In the expression x = a + b / c, the division operation b / c is performed before the addition operation a + .... Therefore, b / c is evaluated as 11, and then a + 11 results in 21, not 16.
Example Program 2
Output:-
Explanation: In the code, the expression (a + b) / c is evaluated. According to the operator precedence rules in C++, parentheses () have the highest precedence. Therefore, a + b is first evaluated inside the parentheses to give 32, and then 32 is divided by 2, resulting in 16. Hence, the output is 16.
Example Program 3
Output:-
Explanation: As in the above code the first expression operators ==
and !=
have the same precedence and the associativity is left to right so first ==
and then !=
operator performed.
And in the second expression first !=
(due to ( )
) and then ==
operator performed. So first expression is solve as:
- x = a == b != c
- x = 10 == 22 != 2
- x=0 != 2
- x=1
And second expression is solve as -
- x = a == (b != c)
- x = 10 == (22 != 2)
- x=10 == 1
- x=0
Example Program 4
Output:-
Explanation: As in the above code, the first expression contains >
operator whose associativity is left to right.
Therefore the expression becomes ((a > b) > c)
, which becomes ((0) > 2)
as (10 is not greater than 22 so it returns 0 and 0 is not greater than 2)
, so output is 0. And the second expression contains <
operator whose associativity is also left to right.
Therefore the expression becomes ((a < b) < c)
, which becomes ((1) < 2)
as (10 is greater than 22 and 1 is less than 2) , so output is 1.
Comments In C++
In C++, comments are used to temporarily disable certain lines of code.
- Single-line comments: These comments begin with
"//"
and continue until the end of the line.
- Multi-line comments: These comments start with
/*
and end with*/
. They can span multiple lines.
Single-line comments are generally preferred for short comments and commenting out single lines, while multi-line comments are useful for longer comments or commenting out blocks of code.
Last updated on -