C++ Programming Series: Pointers (Part 4, Last)

Too busy! Too busy! Don’t expect regular and weekly posts from me. I am studying medicine.

In the previous post, we discussed that pointers are actually arrays! This post is to discuss more about pointers, arrays and the arithmetic that can be done with them.

We can do addition and subtraction with pointers. Multiplication and division is not possible! Here is the code giving an example of pointer arithmetic (try to understand it deeply):

int array[] = {20, 30, 40, 50, 60};
int* pArray = array;

cout << *pArray << endl; //Prints 30, same as array[1]

cout << *pArray << endl; //Prints 40, same as array[2]

cout << pArray[2] << endl; //Prints 60, same as array[4]
//pArray[4] will give error or garbage value!

pArray -= 2;
cout << *pArray << endl; //Prints 20, same as array[0]

cout << pArray[4] << endl; //Prints 60. same as array[4]

When we increment a pointer of type int, the address is actually shifted by the number of bytes that an integer consists of. Similarly, when we increment a pointer of type string, the address is shifted 4 bytes forward. The opposite happens when we decrements a pointer.

Consider the code below:

string words[] = { "First", "Second", "Third", "Fourth", "Fifth" };

string* pWords = words;

Now, pWords is pointing towards the memory address of words[0] or “First”. If we add one into it:

pWords++; //or pWords += 1;

…then it will be shifted 4 bytes forwards to reach the next string of the array, words. Or in other words, pWords is now, equivalent to &words[1]. Now, if we subtract one from it, it will get to the same address as before.

C++ is a very flexible language. We can add the numbers into the pointer temporarily like pWords + 3. Now, if pWords is equivalent to &words[0], then pWords + 3 would give us the address equal to &words[3]. If we dereference this memory address, we will get the proper string value, “Fourth” like this:

string words[] = { "First", "Second", "Third", "Fourth", "Fifth" };
string* pWords = words;

//Adding temporarily for getting the memory address of the
//fourth element of array and dereferencing that memory
//address to get the value from there
cout << *(pWords + 3) << endl; //Prints "Fourth"

Isn’t that similar to that?

cout << pWords[3] << endl; //Prints "Fourth"

Yes, they are completely the same! What is happening with pWords[3] is the same as what is happening with *(pWords + 3).

That’s it! Your exercise is to find out what is the output of the code below (without checking it out in the compiler):

int array[] = { 1,2,3,4,5,6,7,8,9,10 };
int* pArray = array;

pArray += 5;
cout << pArray[3] << endl; //Output 1
pArray -= 3;
cout << pArray[4] << endl; //Output 2
cout << *pArray << endl; //Output 3
pArray + 2;
cout << *pArray << endl; //Output 4
pArray += 1;
cout << *(pArray + 1) << endl; //Output 5

That is all pointers for you. Congratulations! You learned the pointers! Time to step ahead…

C++ Programming Series: Pointers (Part 2)

In the previous post, we learned how to get the memory address of a variable and how to define a variable that holds the memory address i.e pointer.

Suppose that there is a variable of type int called number. We initialize it with value equals to 10. Now, suppose that it has a memory address 091 (Sounds ridiculous but it’s just a supposition). This memory address is present somewhere in our device’s memory.

Some of the memory addresses are shown in the table below, along with the values present in each.

Address 090 091 092 093 094 095
Value Garbage number number number number Garbage

Now, we know that number has a memory address 091. Then, why 092, 093 and 094 are also filled with value, number? Well, just think a little on why not 095? 095 is just a garbage value!

Okay, okay! Let me clear this confusion. number is of type int and the size of int is 4 bytes. Each memory address carries 1 byte. Therefore, to fit a variable of type int, it requires 4 neighboring memory addresses.

So, number is having memory addresses, 091, 092, 093 and 094. But the only memory address that is useful to us, is the first one i.e 091. Every variable only knows its first memory address and its size. When we know the first memory address of a variable, we can easily get the value of that variable.

Now, suppose that we have a pointer of type int called pNumber. We initialize it with the memory address of the number (How to get memory address of a variable? By putting ampersand(&) behind it).

Now, the pNumber is also 091. We dereference it (i.e we put an asterisk(*) behind the pNumber) to get the value 10.

Actually, when we dereference the pointer, we are actually, looking up the memory address which in this case, is 091. Pointer of type int will suggest that whatever is present in this memory address will be the starting byte of the variable which is of type int.

Please read the above statement twice! It is a bit tricky!

To make it easy, here’s the same table:

Address 090 091 092 093 094 095
Value Garbage number —–> pNumber number number number Garbage

After looking up the memory address, pointer takes the value which in this case, is 10.

If you try sizeof() for pointer of any type, it will tell you that the size of pointer is 8 bytes (or may be different depending on your device). This is because a pointer consists memory address and memory address is a hexadecimal value. Hexadecimal values are big values! Therefore, every pointer resembles to type long int which is also 8 bytes in size.

We can manipulate with the pointers as well. We will discuss it in the upcoming posts in detail. For now, just get along with pointers and the concept described above. It should not be hard now! There is still a huge ground to cover regarding pointers…

C++ Programming Series: References

I believe that my series is getting complex with every post being published! This has to be done because we should also be getting more complex and more logical with every topic we discuss.

Today’s topic is References. Before proceeding on, let us discuss few problems with functions. The first one is that we don’t know any methods of getting multiple outputs. The second one is that we don’t make any change in the variable that we pass into the function via parameters.

The following code expresses the second problem with functions:

void multiplyBy2(int variable)
  variable *= 2;
  //No returning

int main()
  int variable = 2;
  mulitplyBy2(variable); //This should change the variable's value to 4
  cout << variable << endl; //Prints 2, not 4
  return 0;

NOTE: We can have same names for variables having completely isolated scopes. Note that multiplyBy2 has a parameter called variable and main function also has a variable called variable. Sounds confusing!

We have a solution for that and that is, to return that variable in the function and then, put that into any variable or just call that temporary return value directly.

But we expect the method above to change the variable’s value which is not the case here! Why? Well, the point is that when we pass the variable via the parameter of the function, we are actually copying that variable into another completely new variable. This new variable has a very limited scope i.e we can only access it inside the function.

Let us discuss a very simple example of what copying is:

int value1 = 2;

int value2 = value1; //Here, value1 is copied into value2
value2*=2; //value2 is a different variable; it will not effect value1 in any case!

cout << value1 << endl; //Prints 2, not 4
cout << value2 << endl; //Prints 4

The highlighted codes shows what is actually happening in the function, multiplyBy2() in the example, given above.

How to do it in the way that we want? The answer is right inside the topic of this post: References. There is another way and that one is through Pointers which is way more complex but we will discuss it later on.

What is a reference? Reference is just another name given to the same variable. In our real life, we can have the reference case of a bird called ‘raven’. Raven is a black bird. So, people can refer to ‘raven’ by calling it as ‘black bird’. In a very similar way, variables can have references as well.

//Consider that there is a bird called 'raven'
int raven = 10;

//That 'black_bird' is a reference to 'raven' 
int& black_bird = raven;

//Now, what we do with 'black_bird' is actually,
//what we are doing with 'raven' as well and vice versa...
black_bird*=2; //Both gets 20
raven+=5; //Both gets 25

cout << raven << endl; //Prints 25
cout << black_bird << endl; //Prints 25

The highlighted line shows how to make reference to a variable. It is pretty simple; just put ampersand or ‘&’ after the type of the variable that we are going to refer to.

int& is considered a type which we can call as ‘reference to an integer’. Same will be for any type reference as well.

Time to make some change in the multiplyBy2() function!

//Notice the ampersand before the variable's name
void multiplyBy2(int& variable)
  variable *= 2;

int main()
  int variable = 2;
  mulitplyBy2(variable); //Now, we are not copying, we are referencing!
  cout << variable << endl; //This time, it prints 4
  return 0;

Now that, the second problem is solved, the first problem is solved as well. We can have multiple outputs by having more parameters to the function. These parameters are going to be references and whatever is going to be changed with these references, this change is going to happen with the actual variables which are passed as parameters in the function.

//The first two parameters represent inputs
//and the next three represent outputs
void get3TimesDivision( float number1, float number2,
float& division1, float& division2, float& division3 )
  division1 = number1 / number2;
  division2 = division1 / number2;
  division3 = division2 / number2;

int main()
  //Multiple Outputs using References
  float div1 = 0.0f, div2 = 0.0f, div3 = 0.0f;
  get3TimesDivision( 8.0f, 2.0f, div1, div2, div3 );

  cout << div1 << endl; //Prints 4
  cout << div2 << endl; //Prints 2
  cout << div3 << endl; //Prints 1

  return 0;

Note the point that where we want to have references, we cannot have constants or temporary values there. In the above case, if the parameters, number1 and number2, are references to float, we cannot pass 8.0f and 2.0f into the function. We must pass variables of type float with the respective values, into the function.

That’s all! References are a great way to deal with outputs. Just try to modify all the previous functions that we created together, to have references and not copies. Practice them very well. They are going to be used extensively!

C++ Programming Series: Arrays

Previous two posts are (or just looks like) useless and really, are not interesting. But in this post, you are going to get the reward! Yes, a reward! You are going to learn my favourite thing, favourite in the way that it makes life with programming very easy! We call it: Arrays.

Before proceeding, remember that this post is a very long post because it is very significant.

What is an array? Array is a list of something; group of variables of a specific type. They are group together in a linear way just like ‘3 after and 2 before the 1’.

#include <iostream>
using namespace std;
int main()
  //This is an array of integers which holds 5 elements(variable of type 'int')
  int array[5] = { 5, 10, 15, 20, 25 };

  //Printing all elements of the array using index.
  //Possible indexes are from 0 to 4, not 5 as it don't starts from 1.
  //Anything other than that, would give you error or just garbage values!
  for(int i = 0; i < 5; i++)
    cout << array[i] << endl;

It looks very simple and I hope that you may have got it here! Array of variables can be for any type! It is not necessary to put 5 before 10 and so on, you can put any number for any index. Here is the format of an array declaration:

-type- -name- [-number_of_elements-]; 

It’s too simple to make one. To initialize every element of an array, there is another method. Just like we output the element of an array via the index, we can alter that number as well!

int array[5]; //Only declaration

for(int i = 1; i <= 5; i++)
  array[i-1] = i*5; //i-1 as index to get a proper range of 0-4 instead of 1-5
//array is now = 5, 10, 15, 20, 25

array[0] = 10; //previous value = 5
array[1] *= 100; //previous value = 10
array[2] -= 5; //previous value = 15
array[3] = 0; //previous value = 20
array[4] %= 5; //previous value = 25

It might be possible that the for-statement and %= may look unclear to you. If that is the case, please check out my previous posts on C++ Programming Series to remember them.

Arrays are just a list of elements with the number of elements or range of indexes unalterable or constant. We can’t change the total number of elements in an array! But there are arrays which can have alterable number of elements; this term is associated with STL or C++ Standard Template Library which we will talk about later.

In the first block of this post, it is not necessary to type in the total number of variables inside the square brackets as the compiler can check that by the number of elements in between the curly brackets. It is not possible to initialize only one or two variables in between the curly brackets, we must initialize all variables in such a case.

Now, we are going to discuss a small case of arrays to pinpoint two things: its importance and the sizeof() operator’s importance (yeah, that useless sizeof()!)

Suppose that we are going to make a game with many enemies. Lets say that they are just 100 in count and we need to have a variable that holds the health for each!

Lets us try to do it without arrays. In the main(or int main()) method:

int enemy1_HP = 10;
int enemy2_HP = 10;
int enemy3_HP = 10;
//and so on to...
int enemy99_HP = 10;
int enemy100_HP = 10;


OK? Is that OK? If your answer is ‘No’, then you really don’t like to work hard. But if it is ‘Yes’, then I should have told you that you also need a variable for the position, speed, attack, bullets, coins… and more. Just with the mentioned ones, there will be about 500 lines of code! That is one of the reasons why we should not measure a programmer’s capability by the number of lines in his/her program.

Apart from the problem of having a lot of lines being wasted on variable declaration, there is an even bigger problem! Just tell me, how are you supposed to combine your 100 enemies’ variables with the looping? I mean that there is nothing like index in a large list of singleton variables. It will just get more and more complex!

In short, it will take enough time to complete the game without arrays that we will begin to hate programming. Of course, it is NOT OK at all!

Here is with arrays:

//Replacing 100 lines with just 3!
int enemyHP[100];
for(int i = 0; i < 100; i++)
  enemyHP[i] = 10;

//I am in love with arrays!

The index can serve as an ID number for the enemy and you can always get and set the health, position, speed, attack, bullets, coins, etc, of the appropriate enemy just by having the ID or index of that enemy.

Now, at the end of the program, for some reason, you want all enemies’ health(or HP) to be equal to zero. Lets say that the program consists of more than 10000 lines of code and 100 files. At the specific line of a specific file, there is the declaration of the enemyHP array. You just forgot the total number of elements in that array. Finding the declaration in the files might take some time. Your IDE have the feature to find the declaration but you don’t know how to access that feature. So, what? We can always use sizeof() to find out the amount of memory allocated by the variable or even array.

In this case, it will give the value 400 for enemyHP array. For each integer, it will have 4 bytes and so, for 100, 400 bytes. So, we need to divide sizeof(enemyHP) by sizeof(int) to get the total amount of elements for that array:

for(int i = 0; i < sizeof(enemyHP)/sizeof(int), i++)
  enemyHP[i] = 0;

And there you go! It is ended and with every post, our database are getting expanded. I can’t just let you go with nothing so, here are some exercises. Strictly speaking, if you are learning programming for the first time with this series of post, just stick with the first 3 exercises. Don’t bother to see the exercises beyond the third one because they might confuse you. The first 3 exercises exercises assumes that you must have some knowledge about console printing, arrays, user input, conditional statements. Just try these 3 exercises. If you get failed to get proper results, try to fix the problems in your code. But after that, if you still get failed, just check out the solution given with the exercise.

To learn how to program stuff is just like to learn how to paint stuff. It just gets better with you, trying to do it, face it and then, experiment with it, again and again, and not just by reading and watching tutorials.

C++ Programming Series: Basic Arithmetic

We discussed many things till now. We discussed about printing the variables, primitive types, user input and some conditional statements. What we should discuss right now is the basic arithmetic.

It is very simple to do primitive calculations with primitive types. We will only work with integers here. But it will be applicable to all other primitive types (of course, ‘char’ is one of them).


int a = 10;
int b = a + 5;
cout << b << endl; //Prints 15

int c = 12;
c = c + 5;
cout << c << endl; //Prints 17

int d = a + c;
cout << d << endl; //Prints 27


int a = 10;
int b = a - 5;
cout << b << endl; //Prints 5

int c = 12;
c = c - 5;
cout << c << endl; //Prints 7

int d = a - c;
cout << d << endl; //Prints 3


int a = 10;
int b = a * 5;
cout << b << endl; //Prints 50

int c = 12;
c = c * 5;
cout << c << endl; //Prints 60

int d = a * c;
cout << d << endl; //Prints 600


int a = 10;
int b = a / 5;
cout << b << endl; //Prints 2

int c = 12;
c = c / 5;
cout << c << endl; //Prints 2
//For integers and characters, remainder is discarded, it is the quotient which is left.
//For floats and doubles, there is no remainder and precise division is done.
//For the above division, it will be 2.4 for floats and doubles.

int d = a / c;
cout << d << endl; //Prints 5

I hope that you might have understood all primitive calculations. One can understand it easily if he/she knows algebra. I will not tell you what is algebra because it is not the purpose of this place. Just Google it if you don’t know. However, there are some short hand methods to some of them, which are really useful. Following are those methods:

int add = 10;
add += 5; //equivalent to "add = add + 5;"

cout << add << endl; //Prints 15

int sub = 10;
sub -= 5; //equivalent to "sub = sub - 5;"

cout << sub << endl; //Prints 5

int mult = 10;
mult *= 5; //equivalent to "mult = mult * 5;"

cout << mult << endl; //Prints 50

int divi = 10;
divi /= 5; //equivalent to "divi = divi / 5;"

cout << divi << endl; //Prints 2

There are two more methods that are very confusing but produces neatness in one’s coding style.

int a = 10;
a++; //equivalent to "a = a + 1;" but with some exceptions
++a; //equivalent to "a = a + 1;" but with some exceptions

cout << a << endl; //Prints 12
//Similar is for subtraction

The first one (a++) is called as postfix increment operator and the other one (++a) is called as prefix increment operator. They are not the same and are very much confused with each other. Similar is the case for postfix and prefix decrement operators (i.e, a--, --a). This can be proved by the code below:

int print = 25;

//Method 1.
//cout << print = print + 1 << endl; //This gives error and so, is not possible.

//Method 2.
cout << print++ << endl; //Prints 25

//Method 3.
cout << ++print << endl; //Prints 27

Awww… What’s that? It’s a strange looking code! But let me explain all this. Both postfix and prefix increment and decrement methods can be placed with variables in a complete C++ code sentence as well. Same is not true for a = a + 1; or a = a - 1;. In the 2nd method, print is first printed out and then, incremented by 1. So, it prints 25 and then, its value is changed to 26 i.e print = print + 1; is done after being printed. In the 3rd method, print is first incremented by 1 and then, is printed out i.e print = print + 1; is done before being printed (Remember, 2nd method already changed its value to 26 and so, in 3rd method, 27 is printed out). The equivalent code to this is given below:

int print = 25;

//"cout << print++ << endl;" is equivalent to
cout << print << endl; //Prints 25
print = print + 1;

//"cout << ++print << endl;" is equivalent to
print = print + 1;
cout << print << endl; //Prints 27

There is another thing. We can have remainder instead of quotient, in dividing numbers by a special operator called as modulo operator, represented by %.

int a = 14;
int b = 5;
cout << a / b << endl; //Prints 2, we can do temporary calculations and print them.
cout << a % b << endl; //Prints 4 which is the remainder obtained by dividing a by b.

a %= a; //a is now, 0.
b %= 3; //b is now, 2.

This post is too lengthy to explain all basic arithmetics in C++. But length don’t matters! It is your motivation and inspiration that matters!

C++ Programming Series: Primitive Types

In the previous post, we discussed variables and a primitive type called as int. Primitive types are the basic types from which other complex things are derived. Like int, following are some other primitive types.

int int_var = 10;
char char_var = 'b';
bool bool_var = true;
float float_var = 24.12f;
double double_var = 248.123;

They have different sizes and they are calculated in bytes which is a term defined for measuring memory in computers. To find out the size of any type or variable, we can use sizeof().

cout << sizeof(int) << endl;
cout << sizeof(bool_var) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double_var) << endl;

Size of int is 4 bytes, char is 1 byte, float 4 bytes and double 8 bytes. They have some value limits as well. For more information, click here.

char is the short form of character, stores a character and bool is the short form of boolean, can only have anyone of the two states, true and false.

float and double allows us to be precise in calculations. The latter one is more precise than the former one. float can have maximum of 7 decimal places whereas double can have maximum of 15 decimal places.

It is always better to use lesser memory or bytes of a computer. int is the most used variable type but it may be a waste if you just want to have it in a very small range of numbers. You can use short or long to increase or decrease the amount of memory allocated by it. For instance, if value of a regular int gets much greater than the limit, use long to have a much greater limit.

short int small_int = 20000;
long int large_int = 20000000;

By default, variables can have positive as well as negative values. There are many cases when negative values are not needed at all. Such variables having both positive and negative values are called as signed variables and those having positive values only are called as unsigned variables.

int i_am_signed_int1 = -100;
signed int i_am_signed_int2 = -250;
unsigned int i_am_unsigned_int3 = 500;

short, long, signed and unsigned aren’t only used with int but can also be used with some other primitive types.

C++ Programming Series: Hello World and Variables

If you already read the previous post and installed Microsoft Visual Studio Express Edition, you can just open it and somewhere, you will see New Solution. Just set a new one and add an empty cpp or source file to it. In this cpp file, copy and paste that code below to it and then, run it. If it runs fine, it will output, “Hello World”, on the console screen.

Here’s the code for printing, “Hello World”:

#include <iostream>
using namespace std;
int main()
 cout << "Hello World" << endl;
 return 0;

The word cout may be taken as a short form of ‘console output’ and endl as ‘end the line’ or put an enter to it. << is an operator called as ‘put to’ operator. Lines of code present between two curly brackets may be taken as a block. There are two statements in the block. Each statement is required to be finished by a semi-colon. main() is the place where codes will run (or execute). For now, this is enough, you will understand the whole of it later on. Don’t worry about this! It looks hard but is very simple.

You can also print numbers and they can be typed in without double commas as well. Just replace “Hello World” with some integer.

cout << 221133 << endl;

Integers are any numbers ranging from infinite negative to infinite positive numbers. But what if we want to store an integer? I mean we may need to call it many times and manipulate its value as well which is hard with a constant like the above one.

To do that, we use variables. To store an integer say 221133 in a variable called as x and then call it later on, we can do something like this:

int x = 221133;
cout << x << endl;

Note that word int. It is the short form of a word called integer. A variable must be written with its type. int or integer is one of them. The cout then, treats x as 221133 which is of type int. Format of any variable is given as:

[type] [name] = [value];

You can declare a variable first and then, give a value to it (initialize it). If you don’t give it a value and print it, you may get an error or most probably, a random value. Therefore, always initialize the variables before using them.

int x;
x = 221133;
cout << x << endl;

The most important thing about the variables is that they have a specific scope. From scope, we mean the area or space where the variable can be used. The scope of a variable is the remaining block after its declaration. If the variable x, is declared in the block below main(), its scope is that block i.e it cannot be used above the declaration or outside the block’s ending flower bracket.

Don’t get panic with all the things here! There is way much more stuff. Try to figure out your learning rate and proceed according to it! Just try to type codes and make them run…