본문 바로가기

Programming/C++ Basic

[Basic C++] 06 - C++ Operators

In this post, I am going to talk about C++ operators allowing you to operate various calculations. There are many operators in C++ but you don't have to memorize all of them. Most operators are just as same as mathematic operators we've learned at school.


Table of Contents

1. Arithmetic Operators

2. Comparison Operators

3. Logical Operators


1. Arithmetic operators

 

There are five basic arithmetic operators in C++ which are Addition, Subtraction, Multiplication, Division, and Modulo (it returns the remainder of a division operation).

 

Code example 1

#include <iostream>

int main()
{
	int a= 10, b=3;

	std::cout << "Addition : " << a + b << std::endl;
	std::cout << "Subtraction : " << a - b << std::endl;
	std::cout << "Mutiplication : " << a * b << std::endl;
	std::cout << "Division : " << a / b << std::endl;
	std::cout << "Modulo : " << a % b << std::endl;
	std::cin.get();
}

Figure 1 Result of code example 1

 

2. Comparison operators

Comparison operators are for comparing two values as it literally sounds. There are five basic comparison operators and they must be located in parenthesis. The return value of the operators is either true or false. The value of false is '0' and anything other than '0' is 'true'. Normally in C++ the number '1' is true.

 

Code example 2

#include <iostream>

int main()
{
	int a= 10, b=3;

	std::cout << "Equal : " << (a == b) << std::endl;
	std::cout << "Not equal to : " << (a != b) << std::endl;
	std::cout << "Less than : " << (a < b) << std::endl;
	std::cout << "Greater than : " << (a > b) << std::endl;
	std::cout << "Less than or equal to : " << (a <= b) << std::endl;
	std::cout << "Greater than or equal to : " << (a >= b) << std::endl;
	std::cin.get();
}

Figure 2 Result of code example 2

 

3. Logical operators

There are three types of logical operators in C++ which are "&& (Ampersand) , || (Vertical bar)". The return value of such operation is a boolean value just like the ones of comparison operators.

 

&& means "and". It only returns "TRUE" when both elements are "TRUE".

|| means "or". It only returns "FALSE" when both elements are "FALSE". Look at the code example below.

 

"\n" is to "space one line". So "\n\n" means "space two lines".

 

The function "boolalpha" returns the textural representation of boolean values instead of the integer values. It does not accept any arguments because the basic role of this function is to turn "boolalpha format flag" on so you can see the boolean texture.

 

Code example 3

#include <iostream>

int main()
{
	int a= true, b=false;

	std::cout << "---The result of && operations---" << std::endl;
	std::cout << "&& Operator for true vs true   = " << std::boolalpha << (a && a) << std::endl;
	std::cout << "&& Operator for true vs false  = " << std::boolalpha << (a && b) << std::endl;
	std::cout << "&& Operator for false vs true  = " << std::boolalpha << (b && a) << std::endl;
	std::cout << "&& Operator for false vs false = " << std::boolalpha << (b && b) << "\n\n";
	std::cout << "---The result of || operations---" << std::endl;
	std::cout << "|| Operator for true vs true   = " << std::boolalpha << (a && a) << std::endl;
	std::cout << "|| Operator for true vs false  = " << std::boolalpha << (a && b) << std::endl;
	std::cout << "|| Operator for false vs true  = " << std::boolalpha << (b && a) << std::endl;
	std::cout << "|| Operator for false vs false = " << std::boolalpha << (b && b) << std::endl;

	std::cin.get();
}

 

Figure 3 Result of example code 3

 

3.1 Short circuit evaluation in C++

Short circuit evaluation in C++ is about not evaluating unnecessary parts of operation if the result is obvious. Since false && whatever() returns false regardless of whatever value you put on the right side of the operation, C++ does not have to evaluate the right side. C++ simply ignores it so it is never executed. Look at example 4. I used a new function called msg (message) just to print out messages. It's a nice way to streamline your code.

 

Code example 4

#include <iostream>

void msg(int a)
{
	std::cout << "The value is = " << a << std::endl;
}

int main()
{
	int a= true, b=false;
	int c = 1;
	std::cout << "--- Short circuit evaluation in C++ ---" << std::endl;
	// Operation 1
	std::cout << "Operation 1 : " << std::boolalpha << ((10 + 5 < 12) && (c++ < 1)) << std::endl;
	msg(c);

	// Operation 2
	std::cout << "Operation 1 : " << std::boolalpha << ((c++ < 1) && (10 + 5 < 12)) << std::endl;
	msg(c);

	std::cin.get();
}

Figure 4 Result of example code 4

Here in this example, the code evaluates two boolean operations. The first one is (10+5 < 12) and the second one is (c++ < 1). The result looks like it tells us that the comparison operator && returned "false" because both operations were false, but it isn't. It returned "false" because the fist operation was false. As soon as the operator checked the first operation, it just skipped the second part.

 

In order to understand this, I wrote the second line of code but this time both operations are switched. Let's see the value of integer 'c'. 

 

* C++ means "increase the value of c by 1

 

You can clearly see that the && operator ignored the second operation (c++), therefore the value of c was the same as before. On the other hand, "c++" operation was executed at the second, and the value of c was changed to 2.

 

4. Conditional or Ternary Operator in C++

Ternary (having three elements, parts, or divisions) operator is for operation with three expressions. It looks complex but the bottom line is very simple as explained in Figure 5.

 

Figure 5 Logic flow of ternary operation

 

Code example 5

#include <iostream>

int main()
{
	int a = 10, b = 5;
	int c = 10;
	// Ternery operation
	std::cout << (a == b ? "Yes !" : "No !") << std::endl;
	std::cout << (a == c ? "Yes !" : "No !");

	std::cin.get();
}

Figure 6 Result of code example 5

I think it's a very self-explanatory example.

 

5. Bitwise operators

Bitwise operators are a little bit more complicated if you are not familiar with binary numbers. Our computers calculate everything as binary numbers which are 0 and 1. In the base-2 numeral, each digit is referred to as a "bit". Bitwise operators are for bit-level operations. Decimal numbers we often use on the screen is changed to binary numbers so the processor can understand your code. Therefore. bitwise operations are faster than basic arithmetic operations (Only for slow processors).

 

There are & (AND), | (OR), ^ (XOR) , ~(NOT), << (Shift left), >> (Shift right) bitwise operators in C++ and each one of them is very similar to logical operator. Look at Table 1 and Table 2.

 

Table 1 Bitwise "AND" operation

A B A & B
1 1 1
1 0 0
0 1 0
0 0 0

 

Table 2 Logical "AND" operation

A B A && B
True True True
True False False
False True False
False False False

 

Code example 7

#include <iostream>

int main()
{
	int a = 10, b = 13, c = 1, d = 2;
	std::cout << "--Bitwise operation--" << std::endl;
	std::cout << " a & b = " << (a & b) << std::endl;
	std::cout << " a ^ b = " << (a ^ b) << std::endl; // Returns only one of the bits is true
	std::cout << " ~a = " << (~a) << std::endl;
	std::cout << " a >> c = " << (a >> c) << std::endl; // One bit to right
	std::cout << " a << c = " << (a << c) << std::endl; // One bit to left
	std::cout << " a >> d = " << (a >> d) << std::endl; // Two bits to right
	std::cout << " a << d = " << (a << d) << std::endl; // Two bits to left

	std::cin.get();
}

Figure 7 Result of code example 7

 

This is a bit hard to understand if you do not really know what bits are. Look at Figure 8. In order to understand bitwise operations, you need to think each bit individually. Most of the bitwise operators are just as same as logical operators except for NOT and SHIFT operators. They are a bit different.

 

NOT (~) operator returns signed two's complement of a given number. Then what is two's complement?. Two's complement of an N-bit number is defined as its complement with respect to 2^N. A complement simply means that a number to be added for a given N-bit number to be 2^N.

 

For example, let's say we have a number 1000 ( 8 ).  2^N of 1000 is 10000 ( 16 ). Two's complement of the given number 1000 ( 8 ) is, thus, 1000. Similarly, Two's complement of 101 is 11. Then it becomes 1000. 

 

One easy method to get two's complement is to get one's complement of a given number and add 1. In order to get one's complement, you can just invert all of the bits of the given number. For instance, one's complement of 101 is 010. This is how a computer processor stores minus values (signed). 

 

A = 10 in Decimal = 0000.....1010 in Binary

One's complement of A is 111111......0101 (all bits are converted).

Two's complement of A is 111111......0110 (one's complement + 1). --> - 11

 

Table 3 Decimal to Binary conversion and bitwise operations

If you want to know how to convert a decimal number to a binary number, refer to the link below. I made a simple C++ code.

https://nalagara.tistory.com/13

 

[Basic C++] Decimal to Binary Converter C++ Code

Here is a simple code converting decimal number to binary number. #include void print_ary(int* ary, int size) // Accept the array pointer and the length of an array { for (int i = 1; i <..

nalagara.tistory.com

Shift operations have two directions; left shift and right shift. The underlying idea is that shift each bit to right or left. Thus a<<1 means, shift every bit of a to right one bit. Similarly, a<<2 means, shift every bit of a to right two bits.

 

 


REFERENCES

(1) http://www.cplusplus.com/doc/tutorial/operators/

(2) https://stackoverflow.com/questions/5211961/how-does-c-handle-short-circuit-evaluation