Operators

In C++, there are symbols which tell the compiler to perform certain operations on variables. These symbols are known as operators. For example, (+) is an operator which is used for adding the values of two variables.

Let's see different types of operators in C++.

Arithmetic Operators

Relational Operators

Increment and Decrement Operators

Logical Operators

Assignment Operators

Arithmetic Operators

Arithmetic Operators are the type of operators which take numerical values (either literals or variables) as their operands and return a single numerical value.

int a = 42, b = 5; - As seen before, this statement declares two integer variables 'a' and 'b' and assigns them the values 42 and 5 respectively.
In the next statement, sum = will be printed as it is, since it is enclosed within " ". After that, the expression ( a + b ) will get evaluated and its value (42 + 5 = 47) will get printed. Thus, sum = 47 will get printed. Similarly, other statements will get evaluated and printed on the screen.

We can also introduce a third variable to store the sum of the first two variables as done in the following example.

This example was just to show you the use of type casting. We converted the integer values of 'x' and 'y' into float in the middle of our program and as per our need.

Precedance of Operators

In Maths, you might have learned about BODMAS rule, but that rule is not applied here. If we have written more than one operation in one line, then which operation should be done first is governed by the following rules :- Expression inside brackets '()' are evaluated first. After that, this table is followed ( The operator at the top has higher precedence and that at the bottom has the least precedence ):

Operator

Associativity

++ -- !

Right to left

* / %

Left to right

+ -

Left to right

> >= < <=

Left to right

== =!

Left to right

&&

Left to right

||

Left to right

= += -= *= /= %=

Right to left

Let's consider an expression

n = 4 * 8 + 7

Since the priority order of multiplication operator ( * ) is greater than that of addition operator ( + ), so first 4 will get multiplied with 8 and after that 7 will be added to the product.

Suppose two operators have the same priority order in an expression, then the evaluation will start from left or right as shown in the above table.

For example, take the expression.

10 / 5 + 2 * 3 -8

Since the priorities of / and * are greater than those of + and -, therefore / and * will be evaluated first. Since / and * have the same priority order, so these will be evaluated from left to right simplifying to the following expression.

2 + 2 * 3 - 8

After /, * will be evaluated resulting in the following expression

2 + 6 - 8

Again + and - have the same precedence, therefore these will also be evaluated from left to right i.e. first 2 and 6 will be added after which 8 will be subtracted resulting in 0.

If you don't want to remember these rules, then just put the expression you want to execute first in brackets. Eg- If you want to divide the product of (2+2) and 444 by the quotient of (999/5), then write the expression as - ((2+2)*444)/(999/5). This will get evaluated as (4*444)/(999/5) and finally get simplified to 1776/199 (as 999/5 is 199 and not 199.8).

Relational Operators

Relational Operators check the relationship between two operands. It returns 1 if the relationship is true and 0 if it is false.

In the above example, since the value of 'a' is not equal to 'b', therefore (a == b) (equal to) returned false and (a !=b) (not equal to) returned true.
Since the value of 'a' is greater than 'b', therefore (a > b) (greater than) and (a >= b) (greater than or equal to) returned true whereas (a < b) (less than) and (a <= b) (less than or equal to) returned false.

Difference between = and ==

Although = and == seem to be same, but they are quite different fromn each other. = is the assignment operator while == is the equality operator.

= assign values from its right side operands to its left side operands whereas == compares values.

Take two examples.

x = 5;

x == 5;

By writing x = 5, we assigned a value 5 to x, whereas by writing x == 5, we checked if the value of x is 5 or not.

Logical Operators

In C++, if we write A and B, then the expression is true if both A and B are true. Whereas, if we write A or B, then the expression is true if either A or B or both are true.

A and B - Both A and B

A or B - Either A or B or both.

The symbol for AND is && while that of OR is ||.

Again assume the value of 'a' to be 8 and that of 'b' to be 4.

Operator

Description

Example

&&

Logical AND. If both the operands are non-zero, then the condition becomes true

(a == b) is false

||

Logical OR. If any one or both the operands are non-zero, then the condition becomes true

(a != b) is true

!

Logical NOT. It is used to reverse the condition. So, if a condition is true, ! makes it false and vice versa.

(a > b) is true

In Logical AND (&&) operator, if any one of the expression is false, the condition becomes false. Therefore, for the condition to become true, both the expressions must be true.

For example, (3>2)&&(5>4) returns true because both the expressions are true. Conditions (3>2)&&(5<4), (3<2)&&(5>4) and (3<2)&&(5<4) are false because atleast one of the expressions are false in each case.

For Logical OR (||) operator, the condition is only false when both the expressions are false. If any one expression is true, the condition returns true. Therefore, (3<2)||(5<4) returns false whereas (3>2)||(5<4), (3<2)||(5>4) and (3>2)||(5>4) returns true.

Logical Not (!) operator converts true to false and vice versa. For example, !(4<7) is true because the expression (4<7) is false and the operator ! makes it true.

In the expression(a && b), since the value of 'b' is 0, therefore the condition became false and thus returned 0. Since the value of 'a' is non-zero, therefore the expression (a || b) became true and thus returned 1. The expression (a>b) is true (since the value of 'a' is greater than 'b') and thus the expression !(a>b) became false.

Assignment Operators

Assignment Operators are used to assign values from its right side operands to its left side operands. The most common assignment operator is =.

If we write a = 10; means that we are assigning a value '10' to the variable 'a'.

There are more assignment operators which are listed in the following table.

Operator

Description

Example

=

Assigns value of right operand to left operand

C = A+B is same as C = A + B

+=

Adds the value of right operand to left operand and assigns the final value to the left operand

C += A is same as C = C + A

-=

Subtracts the value of right operand from left operand and assigns the final value to the left operand

C -= A is same as C = C - A

*=

Multiplies the value right operand to left operand and assigns the final value to the left operand

C *= A is same as C = C * A

/=

Divides the value of left operand from right operand and assigns the final value to the left operand

C /= A is same as C = C / A

%=

takes modulus using two operands and assigns the result to the left operand

a = a+1 - '=' operator starts from right. eg.- if a is 4 and b is 5, then a = b will make a to 5 and b will remain 5.
a = a+b; - Similarly, since '+' has higher priority than '=', so, a+b will be calculated first.
In the exact same fashion, in a = a+1, a+1 will be calculated first since + has higher priority than =. Now, the expression will become a = 8 making the value of 'a' equal to 8.
Similarly, a = a-1 will make the value of 'a' equal to 7 again.

To understand this, consider the value of a variable 'n' as 5. Now if we write n +=2, the expression gets evaluated as n = n+2 thus making the value of 'n' as 7 ( n = 5 + 2 ). Let's look at an example where different assignment operators are used.

In the above example, initially, the value of 'a' is 7.
The expression a += 4 gets evaluated as 'a = a+4' thus making the value of 'a' as 11. After this, the expression a -= 4 gets evaluated as 'a = a-4' thus subtracting 4 from the current value of 'a' (i.e. 11) and making it 7 again. Similarly, other expressions will get evaluated.

Increment and Decrement Operators

++ and -- are called increment and decrement operators respectively.

++ adds 1 to the operand whereas -- subtracts 1 from the operand.

a++ increases the value of a variable 'a' by 1 and a-- decreases the value of a by 1.

Similarly, ++a increases the value of 'a' by 1 and --a decreases the value of a by 1.

In a++ and a--, ++ and -- are used as postfix whereas in ++a and --a, ++ and -- are used as prefix.

For example, suppose the value of a is 5, then a++ and ++a changes the value of 'a' to 6. Similarly, a-- and --a changes the value of 'a' to 4.

Difference between Prefix and Postfix

While both a++ and ++a increases the value of 'a', the only difference between these is that a++ returns the value of 'a' before the value of 'a' is incremented and ++a first increases the value of 'a' by 1 and then returns the incremented value of 'a'.

Similarly, a-- first returns the value of 'a' and then decreases its value by 1 and --a first decreases the value of 'a' by 1 and then returns the decreased value.

In a++, postfix increment operator is used with 'a' which first printed the current value of 'a' (8) and then incremented it to 9.
Similarly in ++b, the prefix operator first added one to the current value of 'b' thus making it 9 and then printed the incremented value. The same will be followed for the decremented operators.

sizeof

sizeof() operator is used to return the size of a variable. Suppose we have an integer variable 'i', so the value of sizeof(i) will be 4 because on declaring the variable 'i' as of type integer, the size of the variable becomes 4 bytes.

Look at the following example to find the size of int, char, float and double variables

Here, sizes of character, float and double variables are 1, 4 and 8 bytes respectively, so sizeof operator applied to these returns 1, 4 and 8 respectively. Whenever we declare an integer variable, a space in the memory equal to 4 bytes gets occupied by it. It doesn't matter whether we assign a value to the variable or not, space will allocate. Since, both i and j are integer variables, therefore the sizes of both of these are 4 bytes, regardless of whether a value is assigned to these or not.

Size of the variables will be different for 32 bit and 64 bit compiler.

Here we printed the sizes of int, char, float and double using sizeof operator, same as we did in the previous example, except for the difference that this time we directly passed the name of the datatype in the sizeof operator.

So, now anytime you need to know the size of any datatype, you can do so by using sizeof operator.

Let's do some Math

What if you want to take out the sine, cos or log of a number?

Yes, we can perform such mathematical operations in C++.

If you are not aware of these mathematical functions, then don't go into these and continue your coding.

All these functions are defined in the cmath library. Therefore, to use any such function in our program, we need to include this library in the beginning of our program. For this, we have to include the following code in the beginning of our program.

#include <cmath>

After importing the library, we can enjoy the different mathematical functions in C++.

Let's see some of the mathematical functions.

Function

Description

sin

Calculates the sine value of some angle in radians

cos

Calculates the cosine value of some angle in radians

ceil

Calculates the number which is equal to the integer just greater than the number passed

floor

Calculates the number which is equal to the integer just smaller than the number passed

fmin

Returns the smaller number among the numbers passed to it

fmax

Returns the larger number among the numbers passed to it

fabs

Calculates the absolute value of a number

round

Rounds a float or a double to the nearest integer

sqrt

Calculates the square root of a number

pow

It takes two numbers as parameters and returns the value of the first number raised to the power equal to the second number

log

Returns the logarithm of a number.

Now let's see the examples of some of these functions.

ceil

It calculates the number which is equal to the integer just greater than it. For example, if the number 4.56 is passed to the function, it will return 5.

fabs

It returns the absolute value of the number passed to it. Absolute value of a number is the magnitude of the number with a positive sign. For example, the absolute value of 2 is 2 whereas the absolute value of -2 is also 2.

To take out the absolute value of -5.6, we have to write the following code.