Lecture 4-C++ Operators and Expressions
Lecture 4-C++ Operators and Expressions
We can also define operators as symbols that help us to perform specific mathematical and
logical computations on operands. In other words, we can say that an operator operates the
operands. For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
Operators in C++ can be classified into 6 types:
i. Arithmetic Operators
ii. Assignment Operators
iii. Relational Operators
iv. Logical Operators
v. Bitwise Operators
vi. Other Operators
Operators can further be categorized as; Unary, Binary and Ternary operators.
a) Unary Operators:
Operators that operate or work with a single operand are unary operators. For example:
Increment (++) and Decrement (--) Operators
int val = 5;
cout<<++val; // 6
1|Page
@myco…TCBE 2202 Computing for Civil Engineering
b) Binary Operators:
Operators that operate or work with two operands are binary operators. For example: Addition
(+), Subtraction (-), multiplication (*), Division (/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
a + b;
Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
++ -- Increment (++) and Decrement (--) the value of the object respectively
2|Page
@myco…TCBE 2202 Computing for Civil Engineering
The integer division, in our example, results in a value of 0. It is because the result of the integer
division where both operands are integers is truncated towards zeros. In the expression x / y, x and
y are operands and / is the operator.
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
return 0;
}
Run Code
Output
a + b = 9
a - b = 5
a * b = 14
a / b = 3
a % b = 1
Here, the operators + , - and * compute addition, subtraction, and multiplication respectively as
we might have expected.
3|Page
@myco…TCBE 2202 Computing for Civil Engineering
/ Division Operator:
Note the operation (a / b) in our program. The / operator is the division operator. As we can
see from the above example, if an integer is divided by another integer, we will get the quotient.
(It is because the result of the integer division where both operands are integers is truncated to
whole number). However, if either divisor or dividend is a floating-point number, we will get the
result in decimals.
In C++,
7/2 is 3
7.0 / 2 is 3.5
7 / 2.0 is 3.5
Thus: For division operator, If we want a floating-point result, we need to use the type double and
make sure at least one of the division operands is also of type double: For example;
#include <iostream>
int main()
{
int x = 123;
double y = 456;
double z = x / y;
std::cout << "The value of z is: " << z << '\n';
}
Output:
4|Page
@myco…TCBE 2202 Computing for Civil Engineering
% Modulo Operator:
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the
remainder is 1.
Note: Arithmetic operators are of two types: (i) binary operators (e.g. Addition (+), Subtraction
(-), multiplication (*), Division (/), modulo (%) operators) and (ii) unary operators (e.g.
Increment (++) and Decrement (--) Operators).
Increment and Decrement Operators:
Increment/decrement operators increment/decrement the value of the object. C++ also provides
increment and decrement operators: ++ and -- respectively.
++ increases the value of the operand by 1
-- decreases it by 1
The operators are:
• ++x // pre-increment operator
• x++ // post-increment operator
• --x // pre-decrement operator
• x-- // post-decrement operator
For example,
int num = 5;
// increment operator
++num; // 6
A simple example:
#include <iostream>
int main()
{
int x = 123;
x++; // add 1 to the value of x
++x; // add 1 to the value of x
--x; // decrement the value of x by 1
x--; // decrement the value of x by 1
std::cout << "The value of x is: " << x;
}
5|Page
@myco…TCBE 2202 Computing for Civil Engineering
Both pre-increment and post-increment operators add 1 to the value of our object, and both pre-
decrement and post-decrement operators subtract one from the value of our object. The difference
between the two, apart from the implementation mechanism (very broadly speaking), is that with
the pre-increment operator, a value of 1 is added first. Then the object is evaluated/accessed in
expression. With the post-increment, the object is evaluated/accessed first, and after that, the value
of 1 is added. To the next statement that follows, it does not make a difference. The value of the
object is the same, no matter what version of the operator was used. The only difference is the
timing in the expression where it is used.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 100, result_a, result_b;
return 0;
}
Run Code
Output
result_a = 11
result_b = 99
In the above program, we have used the ++ and -- operators as prefixes (++a and --b). However,
we can also use these operators as postfix (a++ and b--).
6|Page
@myco…TCBE 2202 Computing for Civil Engineering
2. C++ Assignment Operators
The assignment operator = assigns a value to a variable / object: Therefore, in C++, assignment
operators are used to assign values to variables. For example,
// assign 5 to a
a = 5;
The left side operand of the assignment operator is a variable and the right side operand of the
assignment operator is a value. The value on the right side must be of the same data type as the
variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:
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;
i) “=”
This is the simplest assignment operator. This operator is used to assign the value on the right
to the variable on the left.
Example 1:
int main()
{
char mychar = 'c'; // define a char variable mychar
mychar = 'd'; // assign a new value to mychar
int x = 123; // define an integer variable x
x = 456; // assign a new value to x
int y = 789; // define a new integer variable y
y = x; // assing a value of x to it
}
7|Page
@myco…TCBE 2202 Computing for Civil Engineering
ii) Compound Assignment Operators
Compound assignment operators allow us to perform an arithmetic operation and assign a result
with one operator:
+= // compound addition
-= // compound subtraction
*= // compound multiplication
/= // compound division
%= // compound modulo
Example 2:
#include <iostream>
int main()
{
int x = 123;
x += 10; // the same as x = x + 10
x -= 10; // the same as x = x - 10
x *= 2; // the same as x = x * 2
x /= 3; // the same as x = x / 3
std::cout << "The value of x is: " << x;
}
a) “+=”
This operator is the combination of the ‘+’ and ‘=’ operators. This operator first adds the current
value of the variable on left to the value on the right and then assigns the result to the variable on
the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
b) “-=”
This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on
the right from the current value of the variable on left and then assigns the result to the variable
on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
8|Page
@myco…TCBE 2202 Computing for Civil Engineering
c) “*=”
This operator is a combination of the ‘*’ and ‘=’ operators. This operator first multiplies the
current value of the variable on left to the value on the right and then assigns the result to the
variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
d) “/=”
This operator is a combination of the ‘/’ and ‘=’ operators. This operator first divides the current
value of the variable on left by the value on the right and then assigns the result to the variable
on the left.
Example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
#include <iostream>
using namespace std;
int main() {
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
return 0;
}
Run Code
9|Page
@myco…TCBE 2202 Computing for Civil Engineering
Output
a = 2
b = 7
After a += b;
a = 9
Here, > is a relational operator. It checks if a is greater than b or not. If the relation is true, it
returns 1 whereas if the relation is false, it returns 0. Some of the relational operators are;
Operator Meaning Example
== Is Equal To 3 == 5 gives us false
!= Not Equal To 3 != 5 gives us true
> Greater Than 3 > 5 gives us false
< Less Than 3 < 5 gives us true
>= Greater Than or Equal To 3 >= 5 give us false
<= Less Than or Equal To 3 <= 5 gives us true
Example 1
#include <iostream>
using namespace std;
int main() {
int a = 3;
int b = 5;
cout<<(a < b)<< endl; // operator to check if a is smaller than b
return 0;
}
Output:
10 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 2: Relational Operators
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
return 0;
}
Run Code
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
11 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
4. C++ Logical Operators
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.
Logical Operators are used to combine two or more conditions/constraints or to complement the
evaluation of the original condition in consideration. Therefore, the result of the operation of a
logical operator is a Boolean value either true or false.
Logical OR.
expression1 ||
|| True if at least one of the operands is
expression2
true.
Logical NOT.
! !expression
True only if the operand is false.
In C++, logical operators are commonly used in decision making. To further understand the logical
operators, let's see the following examples,
Suppose,
a = 5
b = 8
Then,
12 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example 1: Logical Operators
#include <iostream>
using namespace std;
int main() {
bool result;
return 0;
}
Run Code
13 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0
Operator Description
| Binary OR
^ Binary XOR
14 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing. For example, the bitwise AND operator represented as ‘&’ in
C takes two numbers as operands and does AND on every bit of two numbers. The result of
AND is 1 only if both bits are 1(True).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
15 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Some of them are discussed here:
a. sizeof operator
• sizeof is much used in the C programming language.
• It is a compile-time unary operator which can be used to compute the size of its operand.
• The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
• Basically, the sizeof the operator is used to compute the size of the variable.
b. Comma Operator
• The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
• The comma operator has the lowest precedence of any C operator.
• Comma acts as both operator and separator.
c. Conditional Operator
• The conditional operator is of the form Expression1? Expression2: Expression3
• Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then
we will execute and return the result of Expression2 otherwise if the condition(Expression1)
is false then we will execute and return the result of Expression3.
• We may replace the use of if..else statements with conditional operators.
e. Cast Operator
• Casting operators convert one data type to another. For example, int(2.2000) would return 2.
• A cast is a special operator that forces one data type to be converted into another.
• The most general cast supported by most of the C compilers is as follows − [ (type)
expression ].
f. &,* Operator
• Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
• Pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var.
16 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Operators Precedence in C++:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:
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, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples
Category Operator Associativity
17 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
Example
Try the following example to understand operators precedence concept available in C++. Copy
and paste the following C++ program in test.cpp file and compile and run this program.
Check the simple difference with and without parenthesis. This will produce different results
because (), /, * and + have different precedence. Higher precedence operators will be evaluated
first:
#include <iostream>
using namespace std;
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
cout << "Value of (a + b) * c / d is :" << e << endl ;
e = ((a + b) * c) / d; // (30 * 15 ) / 5
cout << "Value of ((a + b) * c) / d is :" << e << endl ;
e = (a + b) * (c / d); // (30) * (15/5)
cout << "Value of (a + b) * (c / d) is :" << e << endl ;
e = a + (b * c) / d; // 20 + (150/5)
cout << "Value of a + (b * c) / d is :" << e << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of (a + b) * c / d is :90
Value of ((a + b) * c) / d is :90
Value of (a + b) * (c / d) is :90
Value of a + (b * c) / d is :50
Note: Read and write notes about C++ Operator Overloading and C++ Expressions
18 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering
C++ Expression
C++ expression consists of operators, constants, and variables which are arranged according to the
rules of the language. It can also contain function calls which return values. An expression can
consist of one or more operands, zero or more operators to compute a value. Every expression
produces some value which is assigned to the variable with the help of an assignment operator.
If the expression is a combination of the above expressions, such expressions are known as
compound expressions.
19 | P a g e
@myco…TCBE 2202 Computing for Civil Engineering