C++ Basics

From Imperial College Robotics Society
Jump to: navigation, search

This page provides some simple tips and advice for those which are new to programming in C++. This is by no means a full, comprehensive tutorial but several links can be found at the bottom of the page.


Comments are sections of the code which will not be read by the machine. This is extremely useful as it allows the programmer to add sections describing what the code means and the logic behind their approach. For beginners it is recommended that you comment most lines to explain what a particular command does. As you improve you will only need to explain what particular sections of code are doing or what particular variables refer to. If anyone else will be reading your code they will not be able to understand a thing unless you litter it with comments. In short... comment on your damn code!

To create a comment is quite simple in C++. You simply use two slashes: // This will change the colour of the line after it to whatever your compiler is setup to display, as seen bellow. You can put the // further down the line to place a comment on the same line as the code.

  1. This is a normal line and so is read by the machine
  2. // This is a commented line and so is not read by the machine
  3. i=i+1; //this adds 1 to i

However, sometimes it might be useful to comment a block of lines rather than do each line individually. This can be particularly helpful for temporarily deactivating chunks of code. This can be achieved using a slash star (/*) before and a star slash (*/) after your commented block as shown bellow. Likewise this will turn the code between it a different colour.

  1. Normal code
  2. /*
  3. Commented out code
  4. More commented out code
  5. */
  6. More normal code

Main Function

The main section of your code (usually the code that calls other functions) is included in what is known as the main function. For more advanced codes it is recommended that multiple functions are used (see functions further down) however, for simple codes in can all be contained within the main loop. The main function is created as shown bellow using the { and } to define its start and end. It is also recommended to indent the code within functions as this looks nice (although everybody has their own personnel preferences) most compilers will or can be setup to do this automatically. Other commands will require a semi-colon (;) after it, thus specifying the end of that command. Half of your first errors as a beginer will likely be forgetting to put semi-colons in your code.

  1. int main(){
  2.    //this is a comment
  3.    i=i+1;      //remember the semi-colon after a command
  4. }

The code is read line by line by the computer, in the same way you read a book.


No matter what program you are creating you are going to have to use variables, these are a way of storing numbers or text. To define a variable such as an integer, you simply type "int" (or the relevant command as shown in the list bellow) and then type the name of the variable. The variable can be almost anything from a single letter to a long word but cannot contain spaces or some special characters.

  1. int var;  //sets up an integer variable called var

There are many different types of variables, bellow is a list of some of the more common varieties:

  • char - a small integer (0 to 255)
  • int - an integer (-2147483648 to 2147483648)
  • float - a decimal variable (<math>\pm a \times 10^b</math> where a has ~7 s.f and b is +/- 38)
  • string - a variable containing text

Once you have created variables you can perform arithmetic on them as shown bellow.

  1. x=10     //sets x to 10
  2. x=x+1;   //adds 1 to x and stores in x
  4. y=x*3    //multiplies x by 3 and stores in y
  5. y=y/x    //divides y by x and stores in y

C++ also supports other variable types as well as arrays and vectors, however these are beyond the scope of this tutorial. Please see the links at the bottom for advanced and comprehensive tutorials.


To get your code to respond to inputs or do anything meaningful, it is necessary to perform tests on variables and perform selected code if the result is positive. You could for instance store an input in a variable and then perform an action if it is equal to a certain value. To setup a condition you use the command "if" and place the text in brackets as shown bellow. You can then use { and } to mark out the code that will run if it is true. When testing whether a variable is equal to something you must use == as opposed to just =. To test whether a variable is not equal to something use "=!" e.g. if (x=!y){.

  1. if (x==3){    //tests whether x is three
  2.     x=10;     //if it is then set x to 10
  3. }
  5. if (x>y){     //tests whether x is greater than y
  6.     x=5;      //if it is then set x to 5
  7. }

You are also able to perform commands if the test turns out to be false. This is done using the command else as shown below. The code shows a simple sets x to 1 if y=2 and sets it to 0 otherwise.

  1. if (y==2){
  2.     x=1;
  3. }else{
  4.     x=0;
  5. }

One additional thing to bear in mind is that you are able to place if statements within other if statements. This might seem a little complex and if you don't indent your code or comment it will make it extreamly difficult to read and understand. Below is an example of this. The second if statement won't be tested unless the first one is true. This code is the same as the previous one but instead only runs if the input is set to 1.

  1. if (input==1){     //test whether the input is on or not
  2.     if (y==2){
  3.         x=1;
  4.     }else{
  5.         x=0;
  6.     }
  7. }


It is very helpful to get the computer to run a section of code multiple times, or even for ever, as it allows you to save time and not have to rewrite out the same thing again and again and it also allows you to create a program that will run continuously, repeatedly checking for inputs. There are a couple of varieties of loops available but all do a similar job. If you wish to run a small section of code a set number of times then the best method of doing that is with a for loop. An integer variable can be setup and the program continually adds to that variable. This variable can be used purely for counting or can actually play a part in the code.

The command "for" is used. It is then followed by several commands enclosed within brackets. The variable used in this loop can be defined before or you can define it in these brackets in which case you will require a command such as int n=1. The condition upon when to end the loop and continue with the rest of the code is then usually stated e.g. n<10. You then need to specify how the variables change. This could be done within the loop but is usually done here. To simply add 1 use "n++" and to minus 1 use "n--". Below is an example of this where the 10 factorial is worked out and stored in x.

  1. x=1;
  2. for (int n=1; n<=10; n++){
  3.     x=x*n;
  4. }

A while loop is another commonly used loop and can be used in a similar way. However, you define the condition under which the loop continues to run. In this example the loop continues to run, adding 1 to x every time as long as the input equals 0. If it doesn't then the program exits the loop.

  1. while (input==0){
  2.     x=x+1
  3. }

Lets assume that you want your program to run a main section of code forever. This is essential for many programs. Usually the main function contains a continually repeating section of code which will test for inputs and or condition changes and react appropriately. A simple example can be seen bellow where the program sets the output to 1 if the input is 1 and vice versa, continually updating the output.

  1. while (1){
  3. }

There are various other types of loops but they are not covered in this short tutorial.


Functions are essential to larger, more complex programs and although unused in very simple programs they are fundamental to c++ and you will quickly find a use for them. Functions are isolated pieces of code that you can call at any time simply by stating their name. If you wish to calculate factorials at multiple points in your code they a function where you could input the number and retrieve the answer would be ideal instead of having to laboriously copy out that section of code many times. We shall consider a function which multiplies two numbers together (this is a very simple and rather redundant function but it acts to give you the idea) and returns the result. To define the function we must first consider the output. If it is an integer we can use the command "int" again. If your function doesn't return a value then you can use "void". You then give your function a name. This name cannot be another command or include spaces, it is recommended to give it name that is relevant. You will then follow this name with brackets containing the variables you wish to input to the function. If these variables already exist then you can simply put them in the name, if they don't then you must define them within these brackets as shown below. Using the command return we can receive a value that we imputed. To call the function you simply state it with its inputs as shown below.

  1. int multiply(int a,int b){     //function to multiply a and b
  2.     int x;     //sets up internal variable - x won't exist anymore when you exit the function
  3.     x=a*b;
  4.     return (x);   //returns the value of x
  5. }
  7. //main function
  8. int main(){
  9.     int x=5;   //as the x in the function is isolated we can use that variable name without issue
  10.     int y=3;
  11.     int z;
  13.     z=multiply(x,y);   //calls the function with x and y as the input and stores the output in z
  14. }

Variables defined in a function are isolated to that function. This is extremely useful as it allows you to reuse those variable names without having to worry about effecting other sections of code. In the example above we defined the function before the main function so that when we called it the machine knew what we were talking about. However, it is quite common to have the main function at the top of your code and then list functions below. To do this we simply declare what is known as a prototype of the function. This basically tells the machine that the function exists. To do this we use the same code to define the function but instead of then opening it with { and } we just end it with a semi-colon. Observe below:

  1. int multiply(int a,int b);    //prototype of the function
  3. //main function
  4. int main(){
  5.     int x=5;   //as the x in the function is isolated we can use that variable name without issue
  6.     int y=3;
  7.     int z;
  9.     z=multiply(x,y);   //calls the function with x and y as the input and stores the output in z
  10. }
  12. // the function is now after the main loop
  13. int multiply(int a,int b){     //function to multiply a and b
  14.     int x;     //sets up internal variable - x won't exist anymore when you exit the function
  15.     x=a*b;
  16.     return (x);   //returns the value of x
  17. }

Further C++

The following is a list of C++ tutorials that go into more depth than this short introduction.

  • Cplusplus.com very good comprehensive documentation with examples and a forum.