Expressions and Operators in C++: Study Guide For Module No. 4
Expressions and Operators in C++: Study Guide For Module No. 4
Expressions and Operators in C++: Study Guide For Module No. 4
0 10-July-2020
Welcome to this module! By the time that you are reading this, you have been immersed with the identifiers,
variables and data types in C++ programming and started your adventurous journey in programming. Further,
declaration and initialization and assignment including scope and lifetime were also introduced to you in the
previous module. However, the best way to learn to program is through writing programs directly. Thus, ready
your tools and let’s start a new knowledge to enjoy programming!
Introduction
An expression is a combination of literals, variables, operators, and explicit function calls (not shown above)
that produce a single output value. When an expression is executed, each of the terms in the expression is
evaluated until a single value remains (this process is called evaluation). That single value is the result of the
expression.
Here are some examples of different kinds of expressions, with comments indicating how they evaluate:
2 // 2 is a literal that evaluates to value 2
"Hello world!" // "Hello world!" is a literal that evaluates to text "Hello world!"
x // x is a variable that evaluates to the value of x
2+3 // 2 + 3 uses operator + to evaluate to value 5
x=2+3 // 2 + 3 evaluates to value 5, which is then assigned to variable x
std::cout << x // x evaluates to the value of x, which is then printed to the console
Note: Wherever you can use a single value in C++, you can use an expression instead, and the compiler will resolve the expression
down to a single value.
In mathematics, an operation is a mathematical calculation involving zero or more input values (called operands)
that produces a new value (called an output value). The specific operation to be performed is denoted by a
construct (typically a symbol or pair of symbols) called an operator.
For example, as children we all learn that 2 + 3 equals 5. In this case, the literals 2 and 3 are the operands, and
the symbol + is the operator that tells us to apply mathematical addition on the operands to produce the new
value 5.
x = 5;
This statement assigns the integer value 5 to the variable x. The assignment operation always takes place from
right to left, and never the other way around:
x = y;
This statement assigns to variable x the value contained in variable y. The value of x at the moment this
statement is executed is lost and replaced by the value of y.
Consider also that we are only assigning the value of y to x at the moment of the assignment operation.
Therefore, if y changes at a later moment, it will not affect the new value taken by x.
C++ Code
// 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
[Sample Output]
a:4 b:7 0---------------------------------------------------0-0-
This program prints on screen the final values of a and b (4 and 7, respectively). Notice how a was not affected
by the final modification of b, even though we declared a = b earlier.
Assignment operations are expressions that can be evaluated. That means that the assignment itself has a
value, and -for fundamental types- this value is the one assigned in the operation. For example:
y = 2 + (x = 5);
In this expression, y is assigned the result of adding 2 and the value of another assignment expression (which
has itself a value of 5). It is roughly equivalent to:
1 x = 5;
2 y = 2 + x;
x = y = z = 5;
int main() {
int a, b, temp;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
// value of a is assigned to temp
temp = a; // temp will be 2
cout << "temp = " << temp << endl;
return 0;
}
[Sample Output]
temp = 2
a = 9
LEARNING ACTIVITY 1
Try to answer the following by indicating what output each should produce.
Arithmetic operators are used to perform arithmetic operations on variables and data.
operator description
+ addition
- subtraction
* multiplication
/ division
% modulo
x = 11 % 3;
results in variable x containing the value 2, since dividing 11 by 3 results in 3, with a remainder of 2.
int main() {
int a,b;
a=7;
b=2;
return 0;
}
[Sample 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.
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.
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
7.0 / 2.0 is 3.5
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder is 1.
Compound assignment operators modify the current value of a variable by performing an operation on it. They
are equivalent to assigning the result of an operation to the first operand:
and the same for all other compound assignment operators. For example:
int main()
{
int a,b=3;
a=b;
a+=2; // equivalent to a=a+2
cout<<a;
}
[Sample Output]
5
Some expression can be shortened even more: the increase operator (++) and the decrease operator (--) incr
ease or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thu
s:
1 ++x;
2 x+=1;
3 x=x+1;
are all equivalent in its functionality; the three of them increase by one the value of x.
In the early C compilers, the three previous expressions may have produced different executable code depend
ing on which one was used. Nowadays, this type of code optimization is generally performed automatically by t
he compiler, thus the three expressions should produce exactly the same executable code. C++ allows two ve
ry useful operators not generally found in other computer languages. These are the increment and decrement
operators, ++ and --. The operation ++ adds 1 to its operand, and -- subtracts 1.
A peculiarity of this operator is that it can be used both as a prefix and as a suffix. That means that it can be w
ritten either before the variable name (++x) or after it (x++). Although in simple expressions like x++ or ++x, bo
th have exactly the same meaning; in other expressions in which the result of the increment or decrement ope
ration is evaluated, they may have an important difference in their meaning: In the case that the increase oper
ator is used as a prefix (++x) of the value, the expression evaluates to the final value of x, once it is already inc
reased. On the other hand, in case that it is used as a suffix (x++), the value is also increased, but the express
ion evaluates to the value that x had before being increased. Notice the difference:
Example 1 Example 2
x = 3; x = 3;
y = ++x; y = x++;
// x contains 4, y contains 4 // x contains 4, y contains 3
In Example 1, the value assigned to y is the value of x after being increased. While in Example 2, it is the valu
e x had before being increased.
int main() {
int a=10, b=100, result_a, result_b;
[Sample Output]
result_a = 11
result_b = 99
In the above program, we used ++ and -- operator as prefixes. We can also use these operators as postfix.
There is a slight difference when these operators are used as a prefix versus when they are used as a postfix.
LEARNING ACTIVITY 2
Determine what values the following program outputs. Do not compile this program. Just work through it line by
line in your head.
#include<iostream>
using namespace std;
int main()
{
std::cout<<2+3<<”\n”;
int x{6};
int y{x-2};
std::cout<<y<<”\n”;
int z{0};
z=x;
std::cout<<z-x<<”\n”;
return 0;
}
Introduction
In the term relational operator, the word relational refers to the relationship values can have with one another.
Two expressions can be compared using relational and equality operators. For example, to know if two values
are equal or if one is greater than the other.
The result of such an operation is either true or false (i.e., a Boolean value).
1 (7 == 5) // evaluates to false
2 (5 > 4) // evaluates to true
3 (3 != 2) // evaluates to true
4 (6 >= 6) // evaluates to true
5 (5 < 5) // evaluates to false
Of course, it's not just numeric constants that can be compared, but just any value, including, of course,
variables. Suppose that a=2, b=3 and c=6, then:
Be careful! The assignment operator (operator =, with one equal sign) is not the same as the equality
comparison operator (operator ==, with two equal signs); the first one (=) assigns the value on the right-hand to
the variable on its left, while the other (==) compares whether the values on both sides of the operator are equal.
Therefore, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it
to a (that also stores the value 2), yielding true.
LEARNING ACTIVITY 3
Type the code below in your C++ IDE and observe the output. Try to reverse the operator used and share what
your answer.
Introduction
The word logical refers to the ways these relationships can be connected together using the rules of formal
logic. The key to the concept or relational and logical operators is the idea of true or false.
The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and
inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite
Boolean value of evaluating its operand. For example:
The logical operators && and || are used when evaluating two expressions to obtain a single relational result.
The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands
are true, and false otherwise. The following panel shows the result of operator && evaluating the
expression a&&b:
The operator || corresponds to the Boolean logical operation OR, which yields true if either of its operands
is true, thus being false only when both operands are false. Here are the possible results of a||b:
|| OPERATOR (or)
a b a || b
true true true
true false true
false true true
false false false
For example:
1 ( (5 == 5) && (3 > 6) ) // evaluates to false ( true && false )
2 ( (5 == 5) || (3 > 6) ) // evaluates to true ( true || false )
When using the logical operators, C++ only evaluates what is necessary from left to right to come up with the
combined relational result, ignoring the rest. Therefore, in the last example ((5==5)||(3>6)), C++ evaluates first
whether 5==5 is true, and if so, it never checks whether 3>6 is true or not. This is known as short-circuit
evaluation, and works like this for these operators:
Operator Short-circuit
if the left-hand side expression is false, the combined result is false (the right-hand side
&&
expression is never evaluated).
if the left-hand side expression is true, the combined result is true (the right-hand side
||
expression is never evaluated).
This is mostly important when the right-hand expression has side effects, such as altering values:
Here, the combined conditional expression would increase i by one, but only if the condition on the left
of && is true, because otherwise, the condition on the right-hand side (++i<n) is never evaluated.
The comma operator (,) is used to separate two or more expressions that are included where only one
expression is expected. When the set of expressions has to be evaluated for a value, only the right-most
expression is considered.
a = (b=3, b+2);
would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain
the value 5 while variable b would contain value 3.
Bitwise operators modify variables considering the bit patterns that represent the values they store.
Type casting operators allow to convert a value of a given type to another type. There are several ways to do
this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to
1 int i;
2 float f = 3.14;
3 i = (int) f;
The previous code converts the floating-point number 3.14 to an integer value (3); the remainder is lost. Here,
the typecasting operator was (int). Another way to do the same thing in C++ is to use the functional notation
preceding the expression to be converted by the type and enclosing the expression between parentheses:
i = int (f);
Both ways of casting types are valid in C++.
This operator accepts one parameter, which can be either a type or a variable, and returns the size in bytes of
that type or object:
x = sizeof (char);
Here, x is assigned the value 1, because char is a type with a size of one byte.
The value returned by sizeof is a compile-time constant, so it is always determined before program execution.
LEARNING ACTIVITY 4
In a ¼ sheet of paper, evaluate the program below and provide the expected output.
int main() {
bool result;
return 0;
}
I.II.x = 5 + 7 % 2;
In C++, the above expression always assigns 6 to variable x, because the % operator has a higher
precedence than the + operator, and is always evaluated before. Parts of the expressions can be enclosed in
parenthesis to override this precedence order, or to make explicitly clear the intended effect. Notice the
difference:
III.IV.
1 x = 5 + (7 % 2); // x = 6 (same as without parenthesis)
2 x = (5 + 7) % 2; // x = 0
V.
From greatest to smallest priority, C++ operators are evaluated in the following order:
When an expression has two operators with the same precedence level, grouping determines which one is
evaluated first: either left-to-right or right-to-left.
Enclosing all sub-statements in parentheses (even those unnecessary because of their precedence) improves code readability.
SUMMARY
In this section, we have covered the expressions and operators that could be used in creating C++ programs.
Try to practice the given examples and reverse the operators used. Observe the new output after incorporating
the reverse. Try to remember all the operators as we will be using them in the next modules. Arithmetic operators
are useful in creating basic problem-solving programs. Relational operators often used in decision making
programs and as well as the logical operators.
REFERENCES