Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,357 Categories: 12

Total Tutorial Views: 42,404,625

C++ Beginners Tutorial: Advanced Operators.

Tutorial Name: C++ Beginners Tutorial: Advanced Operators.  

Category: PC Tutorials

Submitted By: Nissan

Date Added:

Comments: 2

Views: 3,337

Related Forum: PC Building Forum

Share:

C++ Beginners Tutorial: Advanced Operators.


We have already come across a fairly large amount of operators; the mathematical operators, +, -, /, --, ++, % and *, the stream operators >> and <<, and the comparison operators, ==, !=, < and >. This is by no means the complete list of every operator C++ has to offer, however. In this section we will learn about several new operators, and go into more depth about a previous one.

Modulo

We touched upon the modulo, or modulus division operator a while back in the first section on operators, however we did not really go that in-depth with it. The modulo operator % returns the remainder, instead of the result, of a division operation. For example, 10 % 3 would give you 1, as 3 divides into 10 3 times with 1 left over. This may not seem entirely helpful, or that's what I though when I first learned of it, as normally we don't use remainders when dividing, we use a decimal point, however it does have a handy use; checking whether a number is even or odd, or more generally, whether it is a multiple of specific number.

For example, if we wanted a program that would tell a user whether a number was even or odd, then we could use the code below:


int userInput = 0;
 
cin >> userInput;
 
if(userInput % 2 == 0)
{
    cout << "Even!\n";
}
else
{
    cout << "Odd!\n";
}


Here, we are dividing the user's input by 2 and checking the remainder. If it is 0, then that number must be a multiple of 2 and so must be even. If not, then it's odd.

Logical Operators

The logical operators are used in conditionals to combine multiple conditions together. For example, say we wanted to check the state of two numbers. If the first was 1, and the second was 2, then some code would be executed. Up until now, we would do it like this:


int a = 1;
int b = 2;
 
if(a == 1)
{
    if(b == 2)
    {
        cout << "A is 1 and B is 2!\n";
    }
}


It works, but it's very unwieldy and ugly. Luckily, C++ provides us a better way of doing it:


int a = 1;
int b = 2;
 
if(a == 1 && b == 2)
{
    cout << "A is 1 and B is 2!\n";
}


We have saved several lines of code and an indentation level by combining two if statements into one larger one. You'll seen that we have used the && operator; the logical and operator. This operator basically says, 'if the condition to the left of me is true, and the condition to the right of me is true, then I shall be true. If not, I will be false.' You can have any number of these in one conditional, they will all work together. There is a catch, however. Whilst it is irrelevant when only using && operators, when you use more (yes, there are more!) the order they are evaluated in can make a difference to the outcome, just like the arithmetic operators. Make sure that you specify the order yourself by using parentheses ( ) in those situations. Remember, the innermost statements are evaluated first.

Another logical operator is the || operator, or logical or. This works in exactly the same way as the and, except that it asks whether either statement is true, not whether both are; 'if the left operand is true or the right operand is true, then I am true. If neither is true, I am false.

Lastly, and this is one you have seen traces of before, is the logical not operator, !. We've come across this operator before inside the != operator, and this is because it is doing the same job as when it is on its own; it reverses the truth of the operand to the left. Unlike the other logical operators, it is a unary operator. An example of its use can be seen below:


int a = 1;
 
// Each comparison means the same thing
if(a != 1 || !(a == 1))
{
    cout << "A is not equal to 1!\n";
}


Don't panic at the 'if' statement; there's nothing we haven't seen before. This conditional is asking, 'If a is not equal to 1, or if the inverse of 'a is equal to 1' is true (i.e. 'a is equal to 1' is false) the the conditional will be true and the code will be executed.' In this example the use of ! is obviously useless, although it is useful in many situations, especially complicated comparisons using multiple logical operators.

Bitwise Operators

The bitwise operators are the penultimate group of operators that we will study at this stage. Indeed, there are quite a few more, however they require knowledge of much more advanced topics that we have not covered. Unfortunately the bitwise operators are also relatively complicated, especially if you don't know binary, but only in principal and not in practice. Plus, they aren't actually used that much. That's no excuse not to learn them though!
If you don't know how binary works, I recommend reading our articles on binary as they give a brief summary of what binary is and how computers store numbers; compulsory knowledge for the bitwise operators.

There are six bitwise operators; &, the bitwise and operator, |, the bitwise or operator, ^, the bitwise exclusive or operator, ~, the bitwise not operator, and << and >>, the bitwise left shift and bitwise right shift, respectively. We will cover them one by one, in this order.

All of the bitwise operators, work on a bit-by-bit level, as hinted at by the name, and the & operator is no exception. It takes two operands, one on the left, and one on the right, just like most of the other operators we have seen, and produces a return value. It compares each operand bit-by-bit, and checks the two bits against each other. If both of the bits are equal to 1, then that same bit of its return value will also be a 1. If they are not the same, then that bit will be a 0. This is better explained with a diagram:

[ Register or Signin to view external links. ]

The second bitwise operator is the | operator. This works in the same way as the & operator, except that instead of returning a 1 for a bit if both bits are 1, it will return a 1 if either bit is a 1. Here's another diagram to explain:

[ Register or Signin to view external links. ]

One of the large pitfalls beginners trip into in C++ is mixing up the logical operators and the bitwise operators. They may look similar, but it is important that you get them the correct way around; a single sign is a bitwise operator, a double sign is the logical operator.

Next is ^, the Bitwise exclusive or operator. This is very similar to the | operator, as the name implies, but also as the name implies, it is more exclusive; a bit will only be 1 if just one of the operands is equal to 1. If both are, it just returns a 0. Here's a handy diagram:

[ Register or Signin to view external links. ]

Luckily ^ doesn't have a logical equivalent to be confused about, although if you frequent websites relating to maths on the Internet, you will see the same sign being used as an exponentiation operator; a to the power of b. Whilst this is possible in C++, you do not use that operator! Just when you thought it wasn't going to be confusing any more.

The next operator, ~, is the Bitwise not operator, or Inversion operator. Unlike the others, this is a unary operator; it only takes one operand, the one to the right of it, like so; ~a. This operator works by looping through each of the bits in the operand, and inverting them; if it was a 1, now it's a 0, if it was a 0, now it's a 1. Simple! Here's a graphical illustration:

[ Register or Signin to view external links. ]

The last two operators, << and >> really show how confusing C++ can be compared to other languages. You may be thinking, Wait, aren't they the stream operators?, and you'd be right; they are. But they are also something else; the Bitwise shift operators. This is because whilst >> and << existed in C (the language C++ grew out of), and so were carried into C++, C does not use streams for input and output, and so there was no confusion. C++ however, does use streams, and happened to pick the same operators. I suppose you run out of symbols when creating such a complex language as C++ (or C).

Anyway, back onto their functions. <<, shifts all of the bits in a number left; that is, the 4th bit becomes the 5, the 3rd bit becomes the 4th, the 2nd becomes the 3rd, and so on. But what happens once the 1st has been shifted? Well, it's simply replaced by a 0. Easy, isn't it? >> on the other hand, shifts everything to the right (and easy way to remember this is that the bits move in the direction of the arrows), replacing the last bit with 0 instead of the first.

But how many spaces are the numbers shifted? This is dependent of the operand to the right of the operator; a << b shifts all of the bits in 'a' to the left 'b' times.

Compound Operators

Compound operators are combinations of the equality operator and one other binary operator, an arithmetic operator, a comparison operator or the bitwise operators. Compound operators are used when you want to perform an operation on a variable and store the result in the variable you performed the operation on. That may sound a little confusing, so here is some code to demonstrate:


int a = 2;
 
// These are equivalent
a = a + 4;
a += 4;


Both operations do exactly the same thing; add the number 4 to a and store the result in a, or in other words, assign the number 6 to a. That, in essence, is all that the compound operators are. I hope you agree that the compound version is a lot nicer than the old way of doing it!

Here is a full list of all of the possible compound operators and the long-hand equivalent:

[ Register or Signin to view external links. ]

We have finally covered all of the operators that we can use at this stage.

Ratings

Current rating: 8.20 by 10 users
Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"C++ Beginners Tutorial: Advanced Operators." :: Login/Create an Account :: 2 comments

If you would like to post a comment please signin to your account or register for an account.

NissanPosted:

Daniel nice tutorial man !!! I learned something at least !!!

Thanks I'm glad it helped you.

SkyPosted:

nice tutorial man !!! i learned something atleast !!!