Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Whether you have had C++ before or not, this page is made to give you a brief introduction to it's most important features.

As always, do keep in mind that this is only one of many good tutorials on C++. We highly recommend you to check out other tutorials online as well, as they might explain things from a different point of view or include information that is not included here. Some of these tutorials are:

We will also use hyperlinks to relevant documentation when explaining various topics. We encourage you to get used to using these, as they will definitely help you out later.

Info

Should you have a suggestions to any specific topic that you would like to see included here, please contact us by mail or through the forums.


Info

Want to get better at programming, check out our page Tips and tricks for coding.



Panel
borderColor#dfe1e5
bgColor#eff9ff
borderWidth2
titlePage content

Table of Contents


Getting started

After downloading Visual Studio, it is time to make our first project!

Expand
titleMake new project


Info

Visual Studio 2019 is used in this tutorial.

  1. Open VS and click on Create a new project. Choose then an Empty Project (make sure it is a C++ project)and click Next.
  2. Proceed by giving your project a name (e.g. "MyProject" and a location. Click Create.
  3. Your project will then open. Here, you may edit the layout of VS as you want by dragging the different modules around.
  4. To write our code, we will need a new file in our project. To add a new file, right-click on your project name → Add → New Item. You may also use the shortcut Ctrl + Shift + A.
  5. Choose C++ File (.cpp), rename it if you want and click Add. The difference between a C++ File (.cpp) (often reffered to as only "cpp file" or "source file") and a Header File (.h) is very important and will be discussed later, but for now, just ignore it.
  6. You have now made your first project! Continue reading at this page to learn how C++ is written.

Now that we have made a working project, let's implement the well known Hello World program.

Expand
titleHello World

To get a better understanding of how the code works, we will first implement the complete program and afterwards we will go through it step by step. To run the code, go to Debug → Start debugging/Start Without Debugging.

Code Block
languagecpp
titleHello World
#include <iostream>
using namespace std;

int main() {
	cout << "Hello World!";
	return 0;
}

Info

Be aware of the semicolons.


Alright, time to take a deeper look at the code. The first line is

Code Block
languagecpp
#include <iostream>

In C++, much like in Python, we have to include libraries (headers) to perform certian actions, e.g. writing to file or solving math equations. iostream is the standard input/output streams library that enables us to print to screen (or e.g. a file).

Code Block
languagecpp
using namespace std;

In this example we have chosen to include the line above to make getting into C++ easier. What using namespace std does is to silently insert std:: (std = standard) as a prefix to a lot of our standard functions. In the example above, cout will therefore be interpreted as std::cout. The short answer to why this is necessary is to specifiy where (which library) the function comes from in the case we have multiple functions with the same name. An analogy to this is how two students with the same name "Tom" are differentiated by adding e.g. the first letter of their last name; "Tom H." and "Tom B.".

By specifying the standard namespace for our entire program, we will avoid having to write std:: before many of our functions, which is benefitial when first learning C++. However, note that this shortcut comes with a cost. To learn more about these negatives, read this post on Stack Overflow explaining why it is considered a bad practice.

Code Block
languagecpp
titleHello World, but without using namespace std;
#include <iostream>

int main() {
	std::cout << "Hello World!";
	return 0;
}

Next up is

Code Block
languagecpp
int main() {
	...
	return 0
}

What you see above is an example of a function in C++ (functions will be further covered later). The brackets " { " and " } " are in C++ used to group a block of statements, in this case those within the function main. Other examples where they are used are in e.g. for loops or if else statements. The equivilant to this in MATLAB is then end statement, and in Python it is the whitespace indent.

The special thing about the main function is that in C++, a program shall contain a global function named main, which is the designated start of the program (the only function called when running). This is very different from both Python and MATLAB, where programs can be written without using any functions at all.

To us, it means that every action we want to execute has to be described from within the main function, although you're of course allowed to call on other functions.

Code Block
languagecpp
titleHello World, not using main function -> Error
#include <iostream>
using namespace std;

cout << "Hello World!";

// Lines starting with "//" is a comment
// This code will result in an error when trying to build.

Lastly, we have

Code Block
languagecpp
cout << "Hello World!";
// or, as previously mentioned
std::cout << "Hello World!";

cout is the standard output stream (stands for character output), and is what enables us to write to screen. cout is a statement, where "<<" is the insertion operator indicating what follows is inserted into cout. We will describe this even further in a later section. Also, notice that every statement is terminated with a semicolon ( ; ). Forgetting this is a very common source of error.

Congratulations, we have now not just made a simple program, but we have also dove deeper into the meaning of our code, thus already touching multiple important features in C++. For even more details on the Hello World example, visit this page.

Variables and operators

You are probably familiar from Python or MATLAB that variables can be e.g. integers, floating-points or strings. In C++, variables are handled a bit more carefully. Among other things, we need to declare what type our variable is before we can give it a value.

Expand
titleMore on variablesVariables

As mentioned, variables can not be given any value without first beeing told what kind of data will be stored there. A full list of all variables and their size/precision can be found at the variable documentation, but some of the most used are

Code Block
languagecpp
int myInteger					// e.g. -1, 2, 3 ...
unsigned int myPositiveInteger	// e.g. 0, 1, 2 ...
float myFloat					// e.g. -1.12, 2, 10e2 ...
double myDouble					// similar to float, but in general, float has 7 digits of precision while double has 15.
bool myBool						// 1, 0, true, false
char myChar						// 'a', 'b', 'v' ... One character
string myString					// "a", "Hello", "Hi again" ...			

In the example above, some variables are a bit different.

  • String is not a fundamental type, and has to be included by it's own library, #include <string>
  • Char is in itself only one character, but it may be combined into a type of string using arrays. We will not cover this here, but you may find more information about it on e.g. the char documentation.


When initializating variables in C++, three methods are used:

Code Block
languagecpp
#include <iostream>
using namespace std;

int main() {
	int a(1);		// Method 1
	int b = 2;		// Method 2
	int c{ 3 };		// Method 3

	cout << a << endl << b << endl << c;	// "endl" means "end line" and makes a new line
	return 0;
}
// Output:
// 1
// 2
// 3


When working with different variables, keep in mind how the variable operates. An example of this is the int, which will always round down to the lowest integer.

Code Block
languagecpp
#include <iostream>
using namespace std;

int main() {
	int a = 10;
	int b = 3;
	double c = 3;

	cout << a / b << endl;	// Output: 3, since a and b are ints -> result is an int
	cout << a / c << endl;	// Output: 3.33333, since c is a double -> result is a double
	cout << static_cast<float>(a) / static_cast<float>(b) << endl;	// Output: 3.33333, since we temporarily interpret the variables as floats
																	// To get a double, we may use only one static_cast<double> in the expression.
	return 0;
}

As shown, static_cast< new_type >( expression ) can temporarily convert a variable to another type in order to bypass the limits set by the original type. To read more about other type conversions, visit this page.


Expand
titleOperators

C++ has a lot of operators which when used correctly can make your code very efficient. Considering the scope of these operators, we will only cover the basics here, and leave you to visit further documentation to learn more about other operators, as well as their precedence.

Arithmetic operators

C++ supports five arithmetic operators, shown the the following table:

OperatorDescription
+Addition
-Subtraction
/Division

*

Multiplication
%Modulo

Note that compared to MATLAB or Python, we are in fact "missing" an operator , for exponentiation (power). In C++, this operator is instead included as the function pow( expression, exponent ).

Code Block
languagecpp
titleExample
int x = 3;
int y = 10;	

cout << x * x;		// 9
cout << pow(x, 2);	// 9
cout << 10y % 3x;		// 1


Relational and comparisonal operators

When comparing expressions, the following operators are used:

OperatorDescription
==

Equal to

!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Logical operators

When evaluating logical operators, C++ only evaluates what is necessary to compute a result from left to right.

OperatorDescription
!Not
||Or
&&And


Code Block
languagecpp
titleExample: Logical operators
!true			// Evaluates to false
!(3 == 3)		// Evaluates to false
true || false	// Evaluates to true
true && false	// Evaluates to false
Statements

Increment and

flow control

decrement

Some much used operators in C++ are the increase ( ++ ) and decrease ( - - ) operators, which are equivalent to +=1 and -=1, respectively.

Code Block
languagecpp
int x = 3;
x++;
cout << x;	// 4
x--;
cout << x;	// 3

The increase and decrease operations can be done in several ways, where each of the approaches below are equivalent to the others.

Code Block
languagecpp
x++;
x += 1;
x = x + 1;


x--;
x -= 1;
x = x - 1;

Another interesting feature of these operators is that the ( ++ ) or ( - - ) can be used as either a prefix or a suffix (postfix), i.e. before or after the variable. Both uses will result in the same action, increasing or decreasing the variable by 1, but the difference lies in when the action is executed. By experience, many students find this confusing, so to ease into it, let's have a look at several examples. You may also read more about the difference here.

Code Block
languagecpp
titleprefix vs suffix increment/decrement
// We will only use ++ in the following examples, but the same rules apply to --
// Ex. 1
int x = 4;
int y = x++;

cout << y << endl;	// 4
cout << x << endl;	// 5
// Here, ++ is used as a suffix, hence y is set equal to the value of x before x is increased by 1


// Ex. 2
int x = 4;
int y = ++x;

cout << y << endl;	// 5
cout << x << endl;	// 5
// Here, ++ is used as a prefix, hence x is increased by 1 (now equal to 5) before y is set equal to the value of x


// Ex. 3
int x = 4;

cout << ++x << endl;	// 5
// Here, ++ is used a prefix, hence x is increase by 1 (now equal to 5) before it is printed to the screen


// Ex. 4
int x = 4;

cout << x++ << endl;	// 4
// Here, ++ is used as a suffix, hence the value of x (currently 4) is printed to the screen before it it increased by 1.
// However, if we were to print or use x on the next line, it would have the value 5
cout << x << endl; 		// 5


Statements and flow control

We will now have a look at the selection statments if else and switch case and the iteration statments for loops and while loops, as well as some other statements included in these. Please note that we will assume that you understand how the different statements work in general , thus enabling us to focus more on the syntax, as well some useful tips and tricks. However, if you're completely new to this, or simply want a more detailed walk-through, have a look at the links above.

Expand
titleIf else statement

The if else statement is used to execute a block if and only if a condition is fulfilled.

Code Block
languagecpp
if (x < 0)
	cout << x << " is a negative number" << endl;		// When we only have one line to execute, we don't have to use { ... }
else if (x > 0) {										// This block has more than one line, thus we have to 
	cout << x << " is a positive number" << endl;		   // indicate the beginning and end with " { "  and " } "
	cout << "This is the second line in this block" << endl;
}
else
	cout << x << " is equal to 0" << endl;



Expand
titleWhile loop

The while loop will execute a block of statements as long as an expression is evaluated as true. In C++, the syntax is as following.

Code Block
languagecpp
// Printing the numbers 1 to 10
int x = 1;
while (x <= 10) {
	cout << x << endl;
	x++;
}

// Also printing the numbers 1 to 10, but using the operator "++" in the expression to save space
// Note that this concept is very similiar to a "for loop".
int x = 0;
while (++x < 10) {
	cout << x << endl;
}

Another type of while loop available in C++ is the do-while loop. It behaves very similar to a regular while loop, but instead of evaluating the expression in the beginning, a condition is evaluated at the end. This introduces a functionality to the while loop that may in some cases be very helpful, it makes it execute the block of statements at least one time.

To illustrate a scenario like this, imagine that you want to make a program that asks for your real name until you write something else than "Smith".

Code Block
languagecpp
#include <iostream>
#include <string>	
using namespace std;

int main() {
	string name;
	do {
		cout << "What is your real name?" << endl;
		cin >> name;
	} while (name == "Smith");
	return 0;
}

If we were to do the same task with a regular while loop, we would have to do something like the following.

Code Block
languagecpp
#include <iostream>
#include <string>	
using namespace std;

int main() {
	string name;	// We could also have set "name = Smith" from the beginning, but this is not desired either
	cout << "What is your real name?" << endl;
	cin >> name;
	while (name == "Smith") {
		cout << "What is your real name?" << endl;
		cin >> name;
	}
	return 0;
}



Expand
titleFor loops

A for loop is designed to iterate a given number of times. In C++, the syntax is as following: for ( initialization; condition; increment ) statement. The block of statements will be ran as long as the condition is fulfilled. which is similar to how a while loop works. However, the for loop have included a specific location to handle both initialization and increase, making it preferable to the while loop when the number of iterations is known.

Code Block
languagecpp
// Printing the numbers 1 to 10
for (int x = 1; x < 11; x++) {
	cout << x << endl;
}


// Printing odd numbers from 1 to 10
for (int x = 1; x < 11; x += 2) {
	cout << x << endl;
}


// We may leave one or several fields blank or add several statements to one field as long as we keep the semicolons between.
for (string name; cin >> name, name != "Exit"; ) {		// Will exit if one of the two conditions fails.
	cout << name << endl;
}

Another type of for loop is the range based for loop. It iterates over all elements in a range.

Code Block
languagecpp
// Printing all letters in 'name'.
string name = "John"
for (char x : name) {
	cout << x << " ";
}
// This is printed: "J o h n "

// Also printing all letters in 'name' below each other,
// but here the type of x is automatically detected as the 
// type of elements in name.
string name = "John"
for (auto x : name) {
	cout << x << endl;
}

// Printing all elements in the vector below each other
// To use 'vector', the library "vector" has to be included
vector<int> my_vec = {1, 2, 4};
for (int x : my_vec) {
	cout << x << endl;
}



Expand
titleJump statements

Jump statements enable us to perform jumps to specific locations.

The break statement leaves a loop even though the condition is not fulfilled, hence before it's natural end. E.g. to end an infinite loop.

Code Block
languagecpp
// Printing all numbers from 1 to 10, but we want to stop when we reach 5.
for (int x = 1; x < 11; x++) {
	cout << x << " ";
	if (x == 5)
		break;
}
// This is printed: 1 2 3 4 5

If we have nested loops (loop within a loop), the break statement will only leave the loop it is executed in, not all loops.

The continue statement causes the program to skip the rest of the loop in the current iteration. As with the break statement, only the loop where continue is executed is affected.

Code Block
languagecpp
// Printing all numbers from 1 to 10, except 5.
for (int x = 1; x < 11; x++) {
	if (x == 5) 
		continue;
	cout << x << " ";
}
// This is printed: 1 2 3 4 6 7 8 9 10



Expand
titleSwitch statement

The switch statement is a bit peculiar, so if you have never encountered it before (it is not used in e.g. Python), we recommend you read the more detailed description found here.

The purpose of the statement is to check for a value among a number of possible constant expression. This a procedure that may also be performed using if statements, but as we will see, it is often both more time and space consuming.

Code Block
languagecpp
// Determining what to write based on the value of x
int x = 3;
switch (x) {		// 'x' is the expression we are looking to match.
case 1:				// Each case is paired with a constant to possibly match the expression, here '1'.
	cout << "The number is 1" << endl;
	break;			// Each case has to end with a break statement.
case 2:
	cout << "The number is between 1 and 3" << endl;
	break;
case 3: 
	cout << "3 is the number" << endl;
	break;
default:			// If no specified cases match, the default case is chosen.
	cout << "The number is unknown!" << endl;
	break;
}
// This is printed: 3 is the number

The most common mistake among students when using switch statements is to forget the break statements at the end of each case. Let's take a look at what happens if we should forget this, using the same example as above.

Code Block
languagecpp
// Determining what to write based on the value of x
// We are now missing some break statements.
int x = 1;
switch (x) {		// 'x' is the expression we are looking to match.
case 1:				// Each case is paired with a constant to possibly match the expression, here '1'.
	cout << "The number is 1" << endl;
case 2:
	cout << "The number is between 1 and 3" << endl;
case 3: 
	cout << "3 is the number" << endl;
	break;
default:			// If no specified cases match, the default case is chosen.
	cout << "The number is unknown!" << endl;
	break;
}
// This is printed: The number is 1 (newline) The number is between 1 and 3 (newline) 3 is the number

As we can see, several cases where executed and thus several lines written. This is because the lack of a break in 'case 1' and 'case 2' made the program continue. It was first in 'case 3' a break appeared, making us jump out of the switch statement.

This is what it would look like if we were to do the same task using only if statements. Notice how this method works well with this particular example because it's small, but may be more inefficient when we have a lot of cases.

Code Block
languagecpp
// Determining what to write based on the value of x
int x = 3;
if (x == 1)
	cout << "The number is 1" << endl;
elseif (x == 2)
	cout << "The number is between 1 and 3" << endl;
elseif (x == 3)
	cout << "3 is the number" << endl;
else
	cout << "The number is unknown!" << endl;
}

We will now have a look at the selection statments if else and switch case and the iteration statments for loops and while loops, as well as some other statements included in these. Please note that we will assume that you understand how the different statements work in general (maybe not switch case, as this is not included in Python), thus enabling us to focus more on the syntax, as well some useful tips and tricks. However, if you're completely new to this, have a look at the tutorials linked at the top of this page for an even more detailed introduction.

The if else statement is used to execute a block if and only if a condition is fulfilled.

Expand
titleIf else statement
Code Block
languagecpp
if (x < 0)
	cout << x << " is a negative number" << endl;		// When we only have one line to execute, we don't have to use { ... }
else if (x > 0) {										// This block has more than one line, thus we have to 
	cout << x << " is a positive number" << endl;		   // indicate the beginning and end with " { "  and " } "
	cout << "This is the second line in this block" << endl;
}
else
	cout << x << " is equal to 0" << endl;
ExpandtitleWhile loop





BibTeX Display Table