Commit 3ab0e8b3 authored by GILLES Sebastien's avatar GILLES Sebastien
Browse files

Change year in copyright notice.

parent d1e0e20a
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Getting started with the tutorial](/notebooks/getting_started_with_tutorial.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#About-the-choice-of-a-Jupyter-notebook" data-toc-modified-id="About-the-choice-of-a-Jupyter-notebook-1">About the choice of a Jupyter notebook</a></span></li><li><span><a href="#When-the-notebook-is-not-enough..." data-toc-modified-id="When-the-notebook-is-not-enough...-2">When the notebook is not enough...</a></span></li><li><span><a href="#Few-guidelines-about-Jupyter" data-toc-modified-id="Few-guidelines-about-Jupyter-3">Few guidelines about Jupyter</a></span><ul class="toc-item"><li><span><a href="#Restarting-the-kernel" data-toc-modified-id="Restarting-the-kernel-3.1">Restarting the kernel</a></span></li></ul></li><li><span><a href="#Very-basic-C++-syntax-(in-notebook-and-in-general)" data-toc-modified-id="Very-basic-C++-syntax-(in-notebook-and-in-general)-4">Very basic C++ syntax (in notebook and in general)</a></span><ul class="toc-item"><li><span><a href="#Semicolons" data-toc-modified-id="Semicolons-4.1">Semicolons</a></span></li><li><span><a href="#Blocks" data-toc-modified-id="Blocks-4.2">Blocks</a></span></li><li><span><a href="#Input-/-output" data-toc-modified-id="Input-/-output-4.3">Input / output</a></span></li></ul></li></ul></div>
%% Cell type:markdown id: tags:
## About the choice of a Jupyter notebook
This notebook uses up [xeus-cling](https://xeus-cling.readthedocs.io/en/latest/), a special instance of Jupyter able to run C++ code based upon xeus (tool to build Jupyter kernels for any language) and cling (a creation from CERN to be able to run C++ as an interpreted language).
The reasons for these choices is to really access directly to handle C++ code without the hassle of explaining how to compile and run stuff, which is an especially cumbersome way to start with this (or any really...) language.
This is not to say this tutorial will ignore entirely these topics (see the dedicated [chapter](/notebooks/6-InRealEnvironment/0-main.ipynb), just that we will first focus on C++ code. However keep in mind that this notebook's fancy interpreter is not a typical C++ environment.
Jupyter Xeus-Cling is still under active development: you should really get a recent version and keep it up-to-date. Some examples in this lecture didn't work at first and were properly dealt with with a version one month later!
## When the notebook is not enough...
As we shall see repeatedly, Xeus-cling notebooks are far from being full-proof: some stuff that are perfectly acceptable C++ aren't accepted in them, and some others required work-arounds. When such an issue appears:
* It will be indicated explicitly in the notebook if a specific work around is used. We do not want you to take Jupyter work-arounds as a legit advice on how to write proper C++.
* If Jupyter can't deal with the code, we will use [Coliru](https://coliru.stacked-crooked.com/). Coliru is a C++ online compiler; others are listed [here](https://arne-mertz.de/2017/05/online-compilers/) ([Wandbox](https://wandbox.org/) deserves a shout out as it enables testing the same code with a great variety of compiler versions).
%% Cell type:markdown id: tags:
## Few guidelines about Jupyter
You might not be familiar with Jupyter notebooks, so here are few tips to run it smoothly (the _Help_ menu will help you find more if you need it).
In a Jupyter notebook the content is divided into _cells_, in our case we are using two kind of cells:
* Markdown cells, such as the ones into these very words are written.
* Code cells, which are running code. In these notebooks the chosen kernel is C++17, so the code is C++17 which is interpreted by cling.
There are two modes:
* Edit mode, in which you might change the content of a cell. In this mode the left part of the cell is in green.
* Command mode, in which you might take actions such as changing the type of a cell, create or delete a new one, etc...
To enter in edit mode, simply type on 'Enter'.
To enter in command mode, type 'Esc'.
To execute a cell, type 'Shift + Enter'. For a markdown cell it will edit nicely the content by interpreting the markdown, and for a code cell it will run the code.
In command mode, several handy shortcuts are there; I would recommend especially:
* `a` (add a cell above)
* `b` (add a cell below)
* `x` (cut a cell)
* `M` (change cell mode to Markdown)
The complete list is available in _Help_ > _Keyboard_ shortcut.
If for some reason the code in the notebook seems stuck, you might try to restart the kernel with one of the restart option in the _Kernel_ menu.
### Restarting the kernel
Sometimes something that should work doesn't... In this case try restarting the kernel: it might fix your issue!
%% Cell type:markdown id: tags:
## Very basic C++ syntax (in notebook and in general)
### Semicolons
In C++ most instructions end by a semicolon `;`. If you forget it, the underlying compiler doesn't understand the syntax.
%% Cell type:code id: tags:
``` C++17
{
int foo = 5 // COMPILATION ERROR!
}
```
%% Output
input_line_11:3:16: error: expected ';' at end of declaration
int foo = 5 // COMPILATION ERROR!
 ^
 ;

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
{
int foo = 5; // OK
}
```
%% Cell type:markdown id: tags:
Spaces, end lines and tabulations act as word separators; utterly unreadable code as the one below is perfectly fine from the compiler standpoint:
%% Cell type:code id: tags:
``` C++17
# include <string>
{
int nombre ; nombre = 1
; std::string nom;
nom=
"truc" ;
nombre = 2
;
}
```
%% Cell type:markdown id: tags:
### Blocks
You may have notices the braces `{` and `}` in the examples above. They are here a technicality to make cling interpreter work better in a Jupyter environment, but that is also useful in a real C++ code.
What is between both braces constitute a **block**; variables that are initialized inside are destroyed once the closing brace is past (don't worry - we will come back to that [later](/notebooks/1-ProceduralProgramming/5-DynamicAllocation.ipynb#Stack)).
This is an incredibly useful feature: you may ensure this way that a variable is not kept any longer than necessary. We will come back to this feature (called the **locality of reference** later); let's see why they are useful in a notebook environment.
In C++, at a given scope a same variable can't be defined twice. So for instance if I defined twice a same variable, the compiler will yell about redefinition of a variable:
%% Cell type:code id: tags:
``` C++17
int i = 2; // Should be fine on the first call.
// But if you have executed it already, a new attempt will make the compiler yell.
```
%% Cell type:code id: tags:
``` C++17
int i = 1; // If the cell above was run, compilation error as `i` is already defined.
```
%% Output
input_line_17:2:6: error: redefinition of 'i'
int i = 1; // If the cell above was run, compilation error as `i` is al...
 ^
input_line_16:2:6: note: previous definition is here
int i = 2; // Should be fine on the first call. But if you have execute...
 ^

Interpreter Error:
%% Cell type:markdown id: tags:
The only way to circumvent this is to restart the kernel... and you may then run only one of this cell, and only once.
So you might now see the usefulness of the braces: by putting them I define the variables in a cell in a block, and it is only defined inside this block. Same variable may this way be defined in different cells:
%% Cell type:code id: tags:
``` C++17
{
int i = 2; // Fine
}
```
%% Cell type:code id: tags:
``` C++17
{
int i = 1; // Also fine
}
```
%% Cell type:markdown id: tags:
### Input / output
Inputs and outputs aren't directly a part of the language itself, but are in the standard library (often abbreviated as STL for Standard Template Library even if some purist may well and explain it's not 100 % the same thing...). You therefore need to __include__ a file named `iostream`; doing so will enable the use of the input / output facilities.
%% Cell type:code id: tags:
``` C++17
{
std::cout << "Hello world!" << std::endl; // Should fail (unless you run a cell that includes iostream before)
}
```
%% Output
input_line_26:3:10: error: no member named 'cout' in namespace 'std'
std::cout << "Hello world!" << std::endl; // Should fail (unless yo...
 ~~~~~^

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
std::cout << "Hello world!" << std::endl; // Should work: std::cout and std::endl are now known.
}
```
%% Output
Hello world!
%% Cell type:markdown id: tags:
- `std::cout` is the symbol to designate the standard output
- `std::endl` is the symbol to clean-up the stream and go to next line.
The operator `<<` is used to indicate what you direct toward the stream; here std::cout << "Hello world!" tells to redirect the string toward the standard output.
We will see that a bit more in detail in [a later chapter](/notebooks/1-ProceduralProgramming/6-Streams.ipynb), but printing something is really helpful early on hence this brief introduction here.
%% Cell type:markdown id: tags:
© _CNRS 2016_ - _Inria 2018_
© _CNRS 2016_ - _Inria 2018-2019_
_This notebook is an adaptation of a lecture prepared and redacted by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_
_The present version has been redacted by Sébastien Gilles and Vincent Rouvreau (Inria)_
......
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Procedural programming](/notebooks/1-ProceduralProgramming/0-main.ipynb)
%% Cell type:markdown id: tags:
* [Variables, initialisation, affectation](/notebooks/1-ProceduralProgramming/1-Variables.ipynb)
* [Condition and loops](/notebooks/1-ProceduralProgramming/2-Conditions-and-loops.ipynb)
* [Predefined types](/notebooks/1-ProceduralProgramming/3-Types.ipynb)
* [Functions](/notebooks/1-ProceduralProgramming/4-Functions.ipynb)
* [TP 1](/notebooks/1-ProceduralProgramming/4b-TP.ipynb)
* [Dynamic allocation](/notebooks/1-ProceduralProgramming/5-DynamicAllocation.ipynb)
* [Input/output](/notebooks/1-ProceduralProgramming/6-Streams.ipynb)
* [TP 2](/notebooks/1-ProceduralProgramming/6b-TP.ipynb)
%% Cell type:markdown id: tags:
© _CNRS 2016_ - _Inria 2018_
© _CNRS 2016_ - _Inria 2018-2019_
_This notebook is an adaptation of a lecture prepared and redacted by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_
_The present version has been redacted by Sébastien Gilles and Vincent Rouvreau (Inria)_
......
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Procedural programming](/notebooks/1-ProceduralProgramming/0-main.ipynb) - [Predefined types](/notebooks/1-ProceduralProgramming/1-Variables.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Ordinary-variables" data-toc-modified-id="Ordinary-variables-1">Ordinary variables</a></span><ul class="toc-item"><li><span><a href="#Declaration" data-toc-modified-id="Declaration-1.1">Declaration</a></span></li><li><span><a href="#Initialisation" data-toc-modified-id="Initialisation-1.2">Initialisation</a></span></li><li><span><a href="#Affectation" data-toc-modified-id="Affectation-1.3">Affectation</a></span></li><li><span><a href="#Increment-and-decrement-operators" data-toc-modified-id="Increment-and-decrement-operators-1.4">Increment and decrement operators</a></span></li><li><span><a href="#Comparing-values" data-toc-modified-id="Comparing-values-1.5">Comparing values</a></span></li></ul></li><li><span><a href="#References" data-toc-modified-id="References-2">References</a></span></li><li><span><a href="#Pointers" data-toc-modified-id="Pointers-3">Pointers</a></span><ul class="toc-item"><li><span><a href="#nullptr" data-toc-modified-id="nullptr-3.1"><code>nullptr</code></a></span></li></ul></li><li><span><a href="#Constant-variables-and-pointers" data-toc-modified-id="Constant-variables-and-pointers-4">Constant variables and pointers</a></span></li><li><span><a href="#Arrays" data-toc-modified-id="Arrays-5">Arrays</a></span><ul class="toc-item"><li><span><a href="#Arrays-and-pointers" data-toc-modified-id="Arrays-and-pointers-5.1">Arrays and pointers</a></span></li></ul></li></ul></div>
%% Cell type:markdown id: tags:
## Ordinary variables
%% Cell type:markdown id: tags:
### Declaration
%% Cell type:markdown id: tags:
To be usable in a C++ program, a variable must be declared. This declaration shall include at least the type of
the variable, followed by its name and a semicolon.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int number; // integer variable
double real; // floating-point variable
std::cout << number << std::endl;
std::cout << real << std::endl;
}
```
%% Output
32766
1.37345e-70
%% Cell type:markdown id: tags:
### Initialisation
%% Cell type:markdown id: tags:
Although not mandatory, it is strongly recommended to give a
initial value to your variables, as an expression between brackets.
Not providing an initial value may lead to unexpected behaviour. For instance you can't make hypothesis upon the values of `number` and `real` in the cell above: you might end-up with any value... and someone else might get other values on his computer!
If you give braces without values, a predefined and associated value
to the type is used (usually a form of 0).
If you give nothing , the behaviour is undefined: you might end up with a 0-like value or something
%% Cell type:code id: tags:
``` C++17
{
int nb1 { 1 }; // integer variable set with the value 1
int nb2 {}; // same as int nb2{0};
double pi { 3.14 } ; // real variable
}
```
%% Cell type:markdown id: tags:
C++ actually supports many other historical forms
of initialization, which you will encounter everywhere, including in this tutorial,
with brackets and/or an equal sign. There are some subtile differences
between each other... that you can ignore most of the time.
%% Cell type:code id: tags:
``` C++17
{
int a = 5;
int b(5);
int c = { 5 };
}
```
%% Cell type:markdown id: tags:
In all cases, even if there is an equal sign, it is important to remember
that it is an initialization, not an assignment (this will be
important when we will define our own types).
%% Cell type:markdown id: tags:
### Affectation
A new value is stored in an existing variable using the operator
of assignment `=`. The name of the variable is on the left; the expression
on the right of the `=` sign is evaluated, and its result is assigned to the variable.
%% Cell type:code id: tags:
``` C++17
#include <iostream> // for std::cout and std::endl
{
int a {}, b {}, c {} ; // default initialization; set the values to 0
std::cout << "Default initialization: a = " << a << ", b = " << b << " and c = " << c << std::endl;
a = 4;
b = 7;
c = a + b;
std::cout << "After affectations: a = " << a << ", b = " << b << " and c = " << c << std::endl;
}
```
%% Output
Default initialization: a = 0, b = 0 and c = 0
After affectations: a = 4, b = 7 and c = 11
%% Cell type:markdown id: tags:
It is also possible to define (slightly) more advanced operators of assignments that modify the value currently stored by a simple operation:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a {}, b {}, c {} ; // default initialization; set the values to 0
a += 4; // add 4 to the current value of a
std::cout << "a = " << a << std::endl;
a *= 7; // multiply current value of a by 3
std::cout << "a = " << a << std::endl;
a /= 5; // divide a by 5 and assign the quotient to a
std::cout << "a = " << a << std::endl;
}
```
%% Output
a = 4
a = 28
a = 5
%% Cell type:markdown id: tags:
### Increment and decrement operators
Finally, C++ also provides a shortcut when value is either incremented or decremented by adding `++` or `--` before or after the name of the variable.
* If the sign is placed before the variable, it is a **pre-increment**.
* If the sign is placed after the variable, it is a **post-increment**.
An example is the better way to explain the difference between both:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 5;
int b = 3;
a++; // increment a by 1.
++a; // same, both are actually equivalents here.
int c = a + b;
std::cout << "a = " << a << ", b = " << b << " and c = " << c << std::endl;
c = a-- + b; // first a + b is evaluated, and only then a is decremented.
std::cout << "a = " << a << ", b = " << b << " and c = " << c << std::endl;
c = a + ++b; // first b is incremented, and only then a + b is evaluated.
std::cout << "a = " << a << ", b = " << b << " and c = " << c << std::endl;
}
```
%% Output
a = 7, b = 3 and c = 10
a = 6, b = 3 and c = 10
a = 6, b = 4 and c = 10
%% Cell type:markdown id: tags:
Honestly it's usually better to remove any ambiguity by separating explicitly both operations:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 7;
int b = 3;
int c = a + b;
std::cout << "a = " << a << ", b = " << b << " and c = " << c << std::endl;
--a; // equivalent to a-- but for reasons related to the standard library I advise you to rather use the
// pre-increment form.
c = a + b; // first a + b is evaluated, and only then a is decremented.
std::cout << "a = " << a << ", b = " << b << " and c = " << c << std::endl;
++b; // same: equivalent to b++;
c = a + b; // first a is incremented, and only then a + b is evaluated.
std::cout << "a = " << a << ", b = " << b << " and c = " << c << std::endl;
}
```
%% Output
a = 7, b = 3 and c = 10
a = 6, b = 3 and c = 9
a = 6, b = 4 and c = 10
%% Cell type:markdown id: tags:
### Comparing values
As shown above, `=` is the affectation operator. To compare two values, the symbol to use is `==`.
Other arithmetic operators are:
| Operator | Effect |
|:------------- |:-------------------------------------------:|
| `a == b` | `true` if a and b are equals |
| `a != b` | `true` if a and b are different |
| `a < b` | `true` if a is less than b |
| `a > b` | `true` if a is greater than b |
| `a >= b` | `true` if a is greater than or equal to b |
| `a <= b` | `true` if a is less than or equal to b |
These operators are defined for most ordinary types and may be defined for your own types (we'll see that [later](/notebooks/3-Operators/2-Comparison.ipynb)).
%% Cell type:markdown id: tags:
## References
A reference is a variable that acts as a kind of alias, and provides another name for the same value.
When defining a reference, it must be immediately initialized by
indicating on which variable it should point; it cannot be changed after that.
The syntax is to add a `&` character just after the type:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a { 2 };
int b { a };
b = b + 1;
int& c { a }; // c is a reference to a
std::cout << "Initial values : a = " << a << ", b = " << b << " and c = " << c << std::endl;
b = b + 5;
std::cout << "After b is modified: a = " << a << ", b = " << b << " and c = " << c << std::endl;
c = c + 1 ; //
std::cout << "After c is modified: a = " << a << ", b = " << b << " and c = " << c << std::endl;
a *= 3;
std::cout << "After a is modified: a = " << a << ", b = " << b << " and c = " << c << std::endl;
}
```
%% Output
Initial values : a = 2, b = 3 and c = 2
After b is modified: a = 2, b = 8 and c = 2
After c is modified: a = 3, b = 8 and c = 3
After a is modified: a = 9, b = 8 and c = 9
%% Cell type:markdown id: tags:
Reference is a purely C++ concept that doesn't exist in C.
%% Cell type:markdown id: tags:
## Pointers
A pointer contains the address of another variable. It declares itself by slipping
a `*` character before the name. It can be initialized or not with the address
of another variable. To explicitly extract the address of this other variable,
we use the symbol `&`.
Later, either you want to modify the address stored in the pointer, to which
in this case we use the pointer name directly, or we want to modify the variable
pointed, in which case the name is prefixed with `*`.
We can therefore see the pointer as a kind of redefinable reference.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a { 2 }, b { 10 };
int* p {&a}; // define a pointer p which is initialized with the address of a
std::cout << "Initial values: " << std::endl;
std::cout << "\t p: address = " << p << ", value = " << *p << std::endl;
std::cout << "\t a: address = " << &a << ", value = " << a << std::endl;
std::cout << "\t b: address = " << &b << ", value = " << b << std::endl;
std::cout << std::endl;
*p = *p + 1; // increment the integer value present at address p
std::cout << "After value pointed by p is incremented:" << std::endl;
std::cout << "\t p: address = " << p << ", value = " << *p << std::endl;
std::cout << "\t a: address = " << &a << ", value = " << a << std::endl;
std::cout << "\t b: address = " << &b << ", value = " << b << std::endl;
std::cout << std::endl;
p = &b; // change the address pointed by p
std::cout << "p now points to the address of b:" << std::endl;
std::cout << "\t p: address = " << p << ", value = " << *p << std::endl;
std::cout << "\t a: address = " << &a << ", value = " << a << std::endl;
std::cout << "\t b: address = " << &b << ", value = " << b << std::endl;
}
```
%% Output
Initial values:
p: address = 0x7ffeea882974, value = 2
a: address = 0x7ffeea882974, value = 2
b: address = 0x7ffeea882970, value = 10
After value pointed by p is incremented:
p: address = 0x7ffeea882974, value = 3
a: address = 0x7ffeea882974, value = 3
b: address = 0x7ffeea882970, value = 10
p now points to the address of b:
p: address = 0x7ffeea882970, value = 10
a: address = 0x7ffeea882974, value = 3
b: address = 0x7ffeea882970, value = 10
%% Cell type:markdown id: tags:
### `nullptr`
A pointer can also designate no variables if initialized with the special value
`nullptr`. It is then a mistake to try to access its pointed value (as we shall see later, an [`assert`](/notebooks/5-UsefulConceptsAndSTL/1-ErrorHandling.ipynb#Assert) is a good idea to ensure we do not try to dereference a `nullptr` value).
It is strongly recommended to initialize a pointer when creating it: if you define an uninitialized pointer, it points to an arbitrary area of memory, which can create undefined behaviors that are not necessarily reproducible.
If the pointed area is known at initialization and never changes throughout the program, you should consider a reference rather than a pointer.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int* p = nullptr; // define a null pointer p
std::cout << "\t p: address = " << p << ", value = " << *p << std::endl; // Dereferencing p is misguided!
}
```
%% Output
p: address = 0x0, value =
input_line_16:4:62: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
std::cout << "\t p: address = " << p << ", value = " << *p << std::endl; // Dereferencing p is misguided!
 ^

Interpreter Exception:
%% Cell type:markdown id: tags:
## Constant variables and pointers
When declaring a variable of a predefined type, it is possible to specify its value can't be changed afterward by using the word `const` which may be placed before or after the type:
%% Cell type:code id: tags:
``` C++17
{
const double pi = 3.1415927;
double const pi_2 = 3.1415927; // equally valid; it is just a matter of taste. Mine is to put it before,
// so that is what you will see in the remaining of the tutorial.
pi = 5.; // COMPILATION ERROR!
pi_2 = 7.; // COMPILATION ERROR!
}
```
%% Output
input_line_23:6:8: error: cannot assign to variable 'pi' with const-qualified type 'const double'
pi = 5.; // COMPILATION ERROR!
 ~~ ^
input_line_23:3:18: note: variable 'pi' declared const here
const double pi = 3.1415927;
 ~~~~~~~~~~~~~^~~~~~~~~~~~~~
input_line_23:7:10: error: cannot assign to variable 'pi_2' with const-qualified type 'const double'
pi_2 = 7.; // COMPILATION ERROR!
 ~~~~ ^
input_line_23:4:18: note: variable 'pi_2' declared const here
double const pi_2 = 3.1415927; // equally valid; it is just a matter of taste. Mine is to put it before,
 ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~

Interpreter Error:
%% Cell type:markdown id: tags:
In the case of a pointer, we can declare the pointer itself constant, and/or the value pointed to depending on whether we place the keyword `const` before or after the type name (in this case it applies to the pointed value) or after the character `*` (in this case it applies to the pointer itself):
%% Cell type:code id: tags:
``` C++17
{
int a { 2 }, b { 3 };
int* p { &a }; // Both pointer and pointed values are modifiable.
p = &b; // OK
*p = 5; // OK
}
```
%% Cell type:code id: tags:
``` C++17
{
int a { 2 }, b { 3 };
int* const p { &a }; // Value is modifiable, but not the address pointed to.
*p = 5; // OK
p = &b; // COMPILATION ERROR - if you comment it it will
}
```
%% Output
input_line_74:6:7: error: cannot assign to variable 'p' with const-qualified type 'int *const'
p = &b; // COMPILATION ERROR - if you comment it it will
 ~ ^
input_line_74:4:16: note: variable 'p' declared const here
int* const p { &a }; // Value is modifiable, but not the address pointed to.
 ~~~~~~~~~~~^~~~~~~~

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
{
int a { 2 }, b { 3 };
const int* p { &a }; // Address pointed to is modifiable, but not the underlying value.
p = &b; // OK
*p = 5; // COMPILATION ERROR
}
```
%% Output
input_line_75:7:8: error: read-only variable is not assignable
*p = 5; // COMPILATION ERROR
 ~~ ^

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
{
int a { 2 }, b { 3 };
const int* const p { &a }; // Nothing is modifiable
p = &b; // COMPILATION ERROR
*p = 5; // COMPILATION ERROR
}
```
%% Output
input_line_76:6:7: error: cannot assign to variable 'p' with const-qualified type 'const int *const'
p = &b; // COMPILATION ERROR
 ~ ^
input_line_76:4:22: note: variable 'p' declared const here
const int* const p { &a }; // Nothing is modifiable
 ~~~~~~~~~~~~~~~~~^~~~~~~~
input_line_76:7:8: error: read-only variable is not assignable
*p = 5; // COMPILATION ERROR
 ~~ ^

Interpreter Error:
%% Cell type:markdown id: tags:
**IMPORTANT**: Even if declared `const`, the pointed value is
not intrinsically constant. It just can't be
modified through this precise pointer.
If other variables reference the same memory area and
are not constant, they are able to modify the value:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a { 2 }, b { 3 };
const int* p { &a }; // Address pointed to is modifiable, but not the underlying value.
std::cout << "Value pointed by p (which doesn't allow value modification) is: " << *p << std::endl;
int* p2 {&a}; // Pointer to the same memory area, but no constness here.
*p2 = 10;
std::cout << "Value pointed by p (and modified through p2) is: " << *p << std::endl;
}
```
%% Output
Value pointed by p (which doesn't allow value modification) is: 2
Value pointed by p (and modified through p2) is: 10
%% Cell type:markdown id: tags:
On the other hand, pointers can't be used as a work-around to modify a constant value:
%% Cell type:code id: tags:
``` C++17
{
const int n { 3 };
int* p_n { &n }; // COMPILATION ERROR
const int* p_n2 { &n }; // OK
}
```
%% Output
input_line_25:4:16: error: cannot initialize a variable of type 'int *' with an rvalue of type 'const int *'
int* p_n { &n }; // COMPILATION ERROR
 ^~

Interpreter Error:
%% Cell type:markdown id: tags:
## Arrays
The operator `[]` enables the creation of an array.
**Beware:** In C++, the indexes of an array start at 0.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i[10] ; // Array of 10 integers - not initialised properly!
double x[3] = { 1., 2., 3. } ; // Array of 3 reals.
std::cout << "i[2] = " << i[2] << " (may be gibberish: undefined behaviour due to lack of initialization!)" << std::endl;
std::cout << "i[10] = " << i[10] << " (undefined behaviour: out of range. Warning identifies the issue)" << std::endl ;
std::cout << "x[1] = " << x[1] << " (expected: 2.)" << std::endl ;
}
```
%% Output
input_line_18:7:32: warning: array index 10 is past the end of the array (which contains 10 elements) [-Warray-bounds]
std::cout << "i[10] = " << i[10] << " (undefined behaviour: out of range. Warning identifies the issue)" << std::endl ;
 ^ ~~
input_line_18:3:5: note: array 'i' declared here
int i[10] ; // Array of 10 integers - not initialised properly!
 ^

i[2] = 149375929 (may be nonsense: undefined behaviour due to lack of initialization!)
i[10] = -87424866 (undefined behaviour: out of range. Warning identifies the issue)
x[1] = 2 (expected: 2.)
%% Cell type:markdown id: tags:
Multi-dimensional arrays are also possible:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int k[2][3] { { 5, 7, 0 }, { 3, 8, 9 }};
std::cout << "k[0][0] = " << k[0][0] << " (expected: 5)" << std::endl;
std::cout << "k[1][2] = " << k[1][2] << " (expected: 9)" << std::endl;
int l[2][3] {}; // default initialization of all elements of the array.
std::cout << "l[0][0] = " << l[0][0] << " (expected: 0)" << std::endl;
std::cout << "l[1][2] = " << l[1][2] << " (expected: 0)" << std::endl;
}
```
%% Output
k[0][0] = 5 (expected: 5)
k[1][2] = 9 (expected: 9)
l[0][0] = 0 (expected: 0)
l[1][2] = 0 (expected: 0)
%% Cell type:markdown id: tags:
**IMPORTANT**: so far we have considered only the case of _static_ arrays, for which the size is already known at compilation. We will deal with dynamic ones [later in this tutorial](/notebooks/1-ProceduralProgramming/5-DynamicAllocation.ipynb#Arrays-on-heap) (and also with the standard libraries [alternatives](/notebooks/5-UsefulConceptsAndSTL/3-Containers.ipynb) such as std::vector or std::array which are actually much more compelling).
%% Cell type:markdown id: tags:
### Arrays and pointers
The variable designating an array is similar to a constant pointer pointing to the beginning of the array. Increasing this pointer is like moving around in the array.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i[2] = { 10, 20 } ;
std::cout << *i << " (expected: 10)" << std::endl ;
std::cout << *i + 1 << " (expected: 11)" << std::endl ;
std::cout << *(i + 1) << " (expected: 20)" << std::endl ;
int* j = i; // OK!
++j; // OK!
std::cout << "Value pointed by j is " << *j << " (expected: 20)" << std::endl;
}
```
%% Output
10 (expected: 10)
11 (expected: 11)
20 (expected: 20)
Value pointed by j is 20 (expected: 20)
%% Cell type:markdown id: tags:
© _CNRS 2016_ - _Inria 2018_
© _CNRS 2016_ - _Inria 2018-2019_
_This notebook is an adaptation of a lecture prepared and redacted by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_
_The present version has been redacted by Sébastien Gilles and Vincent Rouvreau (Inria)_
......
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Procedural programming](/notebooks/1-ProceduralProgramming/0-main.ipynb) - [Conditions and loops](/notebooks/1-ProceduralProgramming/2-Conditions-and-loops.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Conditions" data-toc-modified-id="Conditions-1">Conditions</a></span><ul class="toc-item"><li><span><a href="#if-condition-followed-by-a-single-statement" data-toc-modified-id="if-condition-followed-by-a-single-statement-1.1"><code>if</code> condition followed by a single statement</a></span></li><li><span><a href="#if-condition-followed-by-a-block" data-toc-modified-id="if-condition-followed-by-a-block-1.2"><code>if</code> condition followed by a block</a></span></li><li><span><a href="#No-semicolon-at-the-end-of-the-if-condition" data-toc-modified-id="No-semicolon-at-the-end-of-the-if-condition-1.3">No semicolon at the end of the <code>if</code> condition</a></span></li><li><span><a href="#if-...-else-if-...-else" data-toc-modified-id="if-...-else-if-...-else-1.4">if ... else if ... else</a></span></li><li><span><a href="#The-ternary-operator" data-toc-modified-id="The-ternary-operator-1.5">The ternary operator</a></span></li><li><span><a href="#switch-statement" data-toc-modified-id="switch-statement-1.6"><code>switch</code> statement</a></span></li></ul></li><li><span><a href="#Logical-operators" data-toc-modified-id="Logical-operators-2">Logical operators</a></span></li><li><span><a href="#Loops" data-toc-modified-id="Loops-3">Loops</a></span><ul class="toc-item"><li><span><a href="#while-loop" data-toc-modified-id="while-loop-3.1"><code>while</code> loop</a></span></li><li><span><a href="#do...while-loop" data-toc-modified-id="do...while-loop-3.2"><code>do</code>...<code>while</code> loop</a></span></li><li><span><a href="#for-loop" data-toc-modified-id="for-loop-3.3"><code>for</code> loop</a></span><ul class="toc-item"><li><span><a href="#Historical-for-loop" data-toc-modified-id="Historical-for-loop-3.3.1">Historical <code>for</code> loop</a></span></li><li><span><a href="#New-for-loop" data-toc-modified-id="New-for-loop-3.3.2">New <code>for</code> loop</a></span></li></ul></li><li><span><a href="#continue,-break-and-infinite-loop" data-toc-modified-id="continue,-break-and-infinite-loop-3.4">continue, break and infinite loop</a></span></li><li><span><a href="#So-which-loop-should-I-use?" data-toc-modified-id="So-which-loop-should-I-use?-3.5">So which loop should I use?</a></span></li></ul></li></ul></div>
%% Cell type:markdown id: tags:
## Conditions
%% Cell type:markdown id: tags:
### `if` condition followed by a single statement
%% Cell type:markdown id: tags:
In C++, a condition is the `if` command followed by a condition in parenthesis `()`. The single instruction (that ends at the next `;`) _or_ the block (in braces `{}`that follows is then executed only if the condition is true.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 2;
if (a > 0)
std::cout << a << " is greater than 0" << std::endl;
if (a < 0)
std::cout << "This line won't be executed so nothing will be printed." << std::endl;
std::cout << "But this line will be printed: without braces `{}` only the first instruction depends "
"on the condition!" << std::endl;
}
```
%% Cell type:markdown id: tags:
Of course, the precedent is embarrassing but is due to the poor indenting used: you have to remember that in C++ indenting is just for the programmer: it is much easier to read if a program is properly indented, but it doesn't matter from the compiler standpoint!
Our case above would be much clearer however with a more logical indenting and spacing:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 2;
if (a < 0)
std::cout << "This line won't be executed so nothing will be printed." << std::endl;
std::cout << "It's much clearer now that this line is not encompassed by the condition!" << std::endl;
}
```
%% Output
It's much clearer now that this line is not encompassed by the condition!
%% Cell type:markdown id: tags:
### `if` condition followed by a block
And if you need several lines to be encompassed by the condition, just use braces!
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 2;
if (a < 0)
{
std::cout << "Should not be printed: the condition is false!" << std::endl;
++a; // won't be executed: the condition is false
}
std::cout << "a was not modified and is still 2" << std::endl;
}
```
%% Output
a was not modified and is still 2
%% Cell type:markdown id: tags:
### No semicolon at the end of the `if` condition
__BEWARE__: do not put a `;` at the end of an `if` statement! If you do so, the statement executed if the condition is true is the empty statement `;` which doesn nothing... The risk is rather mitigated: any compiler worth its salt will warn you if you do this mistake.
%% Cell type:code id: tags:
``` C++17
{
int a = 2;
if (a == 0);
std::cout << "Will be printed: the statement after the condition is ';', which does nothing..." << std::endl;
}
```
%% Output
input_line_11:4:16: warning: if statement has empty body [-Wempty-body]
if (a == 0);
 ^
input_line_11:4:16: note: put the semicolon on a separate line to silence this warning
Will be printed: the statement after the condition is ';', which does nothing...
%% Cell type:code id: tags:
``` C++17
{
int a = 2;
if (a == 2)
; // putting the semicolon in a different line silences the warning; there are legitimate cases in
// which it's useful to do so and the risk is
// slim this was written by mistake.
}
```
%% Cell type:markdown id: tags:
### if ... else if ... else
It is rather usual to foreseen two (or more...) courses of action depending on the results of one or several conditions. The syntax in this case is the following:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 2;
if (a < 0)
std::cout << a << " is negative." << std::endl;
else if (a == 0)
{
std::cout << a << " is zero." << std::endl;
}
else if (a < 10)
std::cout << a << " is positive but lower than 10." << std::endl;
else if (a < 100)
std::cout << a << " is in the interval [10, 20[." << std::endl;
else
{
std::cout << a << "is greater than 20." << std::endl;
}
}
```
%% Cell type:markdown id: tags:
Please notice that:
* `else if` and `else` syntax is the same as the one for `if` and you may choose a single statement or a block in each branch of the condition.
* As soon as one condition is fulfilled, the execution of the condition blocks ends. I didn't have to spell out in the (a < 100) case that a had to be greater than 10.
%% Cell type:markdown id: tags:
### The ternary operator
%% Cell type:markdown id: tags:
C++ has inherited from C the so-called ternary operator, which is basically an if/else case packed in one line:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i = 5;
std::cout << "Is " << i << " even? -> " << (i % 2 == 0 ? "true" : "false") << std::endl;
}
```
%% Output
Is 5 even? -> false
%% Cell type:markdown id: tags:
It is really the same as:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i = 5;
std::cout << "Is " << i << " even? -> ";
if (i % 2 == 0)
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
}
```
%% Output
Is 5 even? -> False
%% Cell type:markdown id: tags:
There are nonetheless some cases in which a ternary operator performs a task that is not otherwise reachable by an if/else statement; please consider for instance the initialisation of a `const` variable:
%% Cell type:code id: tags:
``` C++17
{
int i = 5;
const int is_strictly_positive = (i > 0 ? 1 : 0);
std::cout << is_strictly_positive << std::endl;
}
```
%% Output
1
%% Cell type:markdown id: tags:
With if/else it doesn't work: both ways to do so that might step in mind are flawed:
%% Cell type:code id: tags:
``` C++17
{
int i = 5;
const int is_strictly_positive;
if (i > 0)
is_strictly_positive = 1; // COMPILATION ERROR: can't assign to const value!
// ...
}
```
%% Output
input_line_67:4:15: error: default initialization of an object of const type 'const int'
const int is_strictly_positive;
 ^
 = 0
input_line_67:7:30: error: cannot assign to variable 'is_strictly_positive' with const-qualified type
'const int'
is_strictly_positive = 1; // COMPILATION ERROR: can't assign to ...
 ~~~~~~~~~~~~~~~~~~~~ ^
input_line_67:4:15: note: variable 'is_strictly_positive' declared const here
const int is_strictly_positive;
 ~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
{
int i = 5;
if (i > 0)
{
const int is_strictly_positive = 1;
}
else
const int is_strictly_positive = 0;
std::cout << is_strictly_positive << std::endl; // COMPILATION ERROR: is_strictly_positive not
// in the current scope.
}
```
%% Output
input_line_68:12:18: error: use of undeclared identifier 'is_strictly_positive'
std::cout << is_strictly_positive << std::endl; // COMPILATION ERROR...
 ^

Interpreter Error:
%% Cell type:markdown id: tags:
### `switch` statement
Very briefly: there is also a `switch` statement that can be used when:
* The variable is an integer, an enum (see [next notebook](/notebooks/1-ProceduralProgramming/3-Types.ipynb#Enumerations)) or might be convertible into one of those.
* The relationship considered is an equality.
I present it quickly in [appendix](/notebooks/7-Appendix/Switch.ipynb) but we do not have yet seen all the elements needed to explain its interest.
%% Cell type:markdown id: tags:
## Logical operators
A condition might be an amalgation of several conditions. The way to glue it is to use logical operators.
The operators are:
* `&&` for the **and** operator.
* `||` for the **or** operator.
* `!` for the **not** operator.
Actually there are so-called __alternative representations__ using the english name directly for each of them but their usage is not widely spread and not advised from a stylistic standpoint (many StackOverflow threads debate on this topic...).
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 2;
int b = 3;
if (a == 2 || b == 5)
std::cout << "Ok: first condition is true." << std::endl;
if (a == 2 or b == 5)
std::cout << "Same as above illustrating the alternative representation." << std::endl;
if (a == 2 && b == 5)
std::cout << "Not printed: one condition is false." << std::endl;
if (!(a < 0))
std::cout << "Ok: a < 0 is false so the `not` operator returns true." << std::endl;
}
```
%% Output
Ok: first condition is true.
Same as above illustrating the alternative representation.
Ok: a < 0 is false so the `not` operator returns true.
%% Cell type:markdown id: tags:
You may combine several of them in a more complex condition. `and` takes precedence over `or`, but anyway it's usually better to disambiguate using parenthesis:
%% Cell type:code id: tags:
``` C++17
{
int a = 2;
int b = 3;
if (a == 5 || a == 2 && b == 3)
std::cout << "(a == 5) and (a == 2 && b == 3) are evaluated separately and the latter is true so this text is printed" << std::endl;
if ((a == 5) || (a == 2 && b == 3))
std::cout << "Same but easier to grasp." << std::endl;
}
```
%% Output
input_line_20:6:26: warning: '&&' within '||' [-Wlogical-op-parentheses]
if (a == 5 || a == 2 && b == 3)
 ~~ ~~~~~~~^~~~~~~~~
input_line_20:6:26: note: place parentheses around the '&&' expression to silence this warning
if (a == 5 || a == 2 && b == 3)
 ^
 ( )

(a == 5) and (a == 2 && b == 3) are evaluated separately and the latter is true so this text is printed
Same but easier to grasp.
%% Cell type:markdown id: tags:
Builtin operators `&&` and `||` perform short-circuit evaluation: they do not evaluate the second operand if the result is known after evaluating the first. Please notice this means these operators aren't commutative!
%% Cell type:code id: tags:
``` C++17
{
int a = 2;
int b = 3;
if (a > 0 || ++b < 10)
std::cout << "b is still " << b << ": as the first operand was true ++b was never evaluated." << std::endl;
b = 3;
if (++b < 10 || a > 0)
std::cout << "b is now " << b << ": the first operand run is not the same..." << std::endl;
}
```
%% Output
b is still 3: as the first operand was true ++b was never evaluated.
b is now 4: the first operand run is not the same...
%% Cell type:markdown id: tags:
Please notice it's true only for built-in operators: later in this tutorial we will deal with operators overloading, and such operators always evaluate both operands.
%% Cell type:markdown id: tags:
## Loops
%% Cell type:markdown id: tags:
### `while` loop
%% Cell type:markdown id: tags:
The `while` instruction allows you to execute a block of instructions in a loop
as long as a condition is true. The condition is checked **before** each
iteration.
The rules about the instructions belonging to the loop are exactly the same as the ones described for `if` statements.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 0;
while (a++ < 5)
std::cout << a << std::endl;
}
```
%% Output
1
2
3
4
5
%% Cell type:markdown id: tags:
If the condition is never true in the first place, we never go inside the loop:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 0;
while (a++ < 0)
std::cout << a << std::endl;
}
```
%% Cell type:markdown id: tags:
### `do`...`while` loop
%% Cell type:markdown id: tags:
The `do` instruction allows you to execute a block of instructions in a loop as long as
that a condition is true. The condition is verified **after** each
iteration.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int a = 0;
do
{
std::cout << a << std::endl;
} while (a++ < 0); // there is a semicolon here.
}
```
%% Output
0
%% Cell type:markdown id: tags:
### `for` loop
%% Cell type:markdown id: tags:
#### Historical `for` loop
%% Cell type:markdown id: tags:
The historical `for` instruction allows you to execute a block of instructions as long as a
condition is true; the difference with the `while` loop is that there are fields explicitly detailing:
* The initial situation.
* The condition to check at the end of each loop.
* What should be changed in next loop is one is called for.
Syntax is:
for (_initial situation_ ; _end loop condition_ ; _evolution for next loop_)
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
for (int i = 0; i < 5; ++i)
std::cout << i << std::endl;
}
```
%% Output
0
1
2
3
4
%% Cell type:markdown id: tags:
Any of these fields might be left empty:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i = 0; // i might also be declared and initialized outside the block
for ( ; i < 5; )
{
++i; // i might also be modified within the block
std::cout << i << std::endl;
}
std::cout << "`for` loop stopped for i = " << i << std::endl;
}
```
%% Output
1
2
3
4
5
`for` loop stopped for i = 5
%% Cell type:markdown id: tags:
#### New `for` loop
%% Cell type:markdown id: tags:
The `for`syntax we just saw is still very useful, but C++ 11 introduced a new syntax when for instance you want to iterate through all the items in a container, clearly taking inspiration from syntax present in languages such as Python:
for (_type_ _element_ : _container_)
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <vector> // we'll present this one more in detail later
{
std::vector<int> v { 2, 3, 5, 7 };
for (int item : v)
std::cout << item << std::endl;
}
```
%% Output
2
3
5
7
%% Cell type:markdown id: tags:
It might not seem much, but just for the record doing the same before C++ 11 was not for the faint of heart...:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <vector> // we'll present this one more in detail later
{
std::vector<int> v { 2, 3, 5, 7 };
for (std::vector<int>::const_iterator it = v.cbegin(), end = v.cend();
it != end;
++it)
{
std::cout << *it << std::endl;
}
}
```
%% Output
2
3
5
7
%% Cell type:markdown id: tags:
### continue, break and infinite loop
%% Cell type:markdown id: tags:
A danger with a loop is to make it infinite: you have to make sure an exit way is foreseen:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
// WARNING: if you run this you will have to restart your kernel! (in Kernel menu)
{
int i = 2;
while (i > 0) // condition that is true for quite a long time...
std::cout << ++i << " ";
}
```
%% Cell type:markdown id: tags:
The best is to write a palatable condition to end it, but when some loops become increasingly complex you may have to resort to `break`. Be aware it is slightly frown upon by some programmers, for the very same reasons [goto](https://en.wikipedia.org/wiki/Goto) instructions are avoided.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i = 2;
while (i > 0)
{
std::cout << i++ << " ";
if (i > 20)
break;
}
}
```
%% Output
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
%% Cell type:markdown id: tags:
In this trivial case writing the condition more properly would be of course much better:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
int i = 2;
while (i > 0 and i <= 20)
std::cout << i++ << " ";
}
```
%% Output
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
%% Cell type:markdown id: tags:
but honestly in more complex cases `break` can help keep the code more readable.
`continue` is related: it is useful when in some conditions you want to skip the remainder of the current loop iteration to go directly to the next:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
for (int i = 2; i < 20; ++i)
{
if (i == 2)
{
std::cout << i << " is even and prime (hello 2!)." << std::endl;
continue;
}
if (i % 2 == 0)
{
std::cout << i << " is even." << std::endl;
continue; // goes directly at the condition checking step in the loop,
// skipping the remaining code below.
}
std::cout << i << " is odd";
bool is_prime = true;
for (int j = 2; j < i / 2; ++j)
{
if (i % j == 0)
{
is_prime = false;
break; // this break cuts the inner loop 'for (int j = 1; j < i / 2; ++j)'
}
}
std::cout << (is_prime ? " and prime." : ".") << std::endl;
}
}
```
%% Output
2 is even and prime (hello 2!).
3 is odd and prime.
4 is even.
5 is odd and prime.
6 is even.
7 is odd and prime.
8 is even.
9 is odd.
10 is even.
11 is odd and prime.
12 is even.
13 is odd and prime.
14 is even.
15 is odd.
16 is even.
17 is odd and prime.
18 is even.
19 is odd and prime.
%% Cell type:markdown id: tags:
Of course, in a trivial example like this one we could have written it much more cleanly without any `continue`, but in more complex cases it is really handful to use it: not using it could lead to code much more complicated to understand, and you really should always strive for code that is the most palatable for a reader.
%% Cell type:markdown id: tags:
### So which loop should I use?
%% Cell type:markdown id: tags:
Whichever you want in fact!
They are mostly interchangeable:
* `while` and (historical) `for` are completely interchangeable, as:
- A `while` loop is exactly like a `for ` loop with only the middle term.
- You can transform the loop into a while: putting the first term before the loop and the third one inside the loop to do so.
* `do..while` behaves slightly differently, but you can always mimic the behaviour with another type of loop.
Lots of programming language define these guys (at least `for` and `while`) so it's useful to know about them, but you can choose one and stick with it as well.
%% Cell type:markdown id: tags:
© _CNRS 2016_ - _Inria 2018_
© _CNRS 2016_ - _Inria 2018-2019_
_This notebook is an adaptation of a lecture prepared and redacted by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_
_The present version has been redacted by Sébastien Gilles and Vincent Rouvreau (Inria)_
......
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Procedural programming](/notebooks/1-ProceduralProgramming/0-main.ipynb) - [Predefined types](/notebooks/1-ProceduralProgramming/3-Types.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Boolean" data-toc-modified-id="Boolean-1">Boolean</a></span></li><li><span><a href="#Enumerations" data-toc-modified-id="Enumerations-2">Enumerations</a></span><ul class="toc-item"><li><span><a href="#Historical-enumerations" data-toc-modified-id="Historical-enumerations-2.1">Historical enumerations</a></span></li><li><span><a href="#New-enumerations" data-toc-modified-id="New-enumerations-2.2">New enumerations</a></span></li></ul></li><li><span><a href="#Numerical-types" data-toc-modified-id="Numerical-types-3">Numerical types</a></span><ul class="toc-item"><li><ul class="toc-item"><li><span><a href="#List-of-numerical-types" data-toc-modified-id="List-of-numerical-types-3.0.1">List of numerical types</a></span></li><li><span><a href="#Numeric-limits" data-toc-modified-id="Numeric-limits-3.0.2">Numeric limits</a></span></li><li><span><a href="#Conversions-between-digital-types" data-toc-modified-id="Conversions-between-digital-types-3.0.3">Conversions between digital types</a></span></li></ul></li><li><span><a href="#Explicit-conversions-inherited-from-C" data-toc-modified-id="Explicit-conversions-inherited-from-C-3.1">Explicit conversions inherited from C</a></span></li><li><span><a href="#Explicit-conversions-by-static_cast" data-toc-modified-id="Explicit-conversions-by-static_cast-3.2">Explicit conversions by static_cast</a></span></li><li><span><a href="#Other-explicit-conversions" data-toc-modified-id="Other-explicit-conversions-3.3">Other explicit conversions</a></span></li></ul></li><li><span><a href="#Characters-and-strings" data-toc-modified-id="Characters-and-strings-4">Characters and strings</a></span><ul class="toc-item"><li><span><a href="#Historical-strings" data-toc-modified-id="Historical-strings-4.1">Historical strings</a></span></li><li><span><a href="#std::string" data-toc-modified-id="std::string-4.2">std::string</a></span></li></ul></li><li><span><a href="#Renaming-types" data-toc-modified-id="Renaming-types-5">Renaming types</a></span></li><li><span><a href="#decltype-and-auto" data-toc-modified-id="decltype-and-auto-6"><code>decltype</code> and <code>auto</code></a></span></li></ul></div>
%% Cell type:markdown id: tags:
## Boolean
Variables with type `bool` may be set to true or false.
It should be noted that this type did not originally exist, and that C++ instructions with conditions do not necessarily expect boolean values, but rather integers.
There is a form of equivalence between booleans and integers: any null integer is equivalent to `false`, and any other value is equivalent to `true`.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
bool a = true, b(false), c{true};
bool d; // UNDEFINED !! - warning: 'd' is used uninitialized in this function [-Wuninitialized]
if (d)
std::cout << "This text might appear or not - it's truly undefined and may vary from "
"one run/compiler/architecture/etc... to another!" << std::endl;
int n = 5;
if (n)
std::cout << "Boolean value of " << n << " is true." << std::endl;
n = 0;
if (!n) // ! is the not operator: the condition is true if n is false.
std::cout << "Boolean value of " << n << " is false." << std::endl;
n = -2;
if (n)
std::cout << "Boolean value of " << n << " is true." << std::endl;
}
```
%% Output
Boolean value of 5 is true.
Boolean value of 0 is false.
Boolean value of -2 is true.
%% Cell type:markdown id: tags:
## Enumerations
### Historical enumerations
The historical enumerations `enum` of C++ allow to define constants that are treated as integers, and that can be initialized from integers. By default the first value is 0 and the `enum` is incremented for each value, but it is possible to bypass these default values and provide the desired numerical value yourself.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
enum color { red, green, blue } ;
std::cout << red << " " << green << " " << blue << " (expected: 0, 1, 2)" << std::endl;
enum shape { circle=10, square, triangle=20 };
std::cout << circle << " " << square << " " << triangle << " (expected: 10, 11, 20)"<< std::endl; // 10 11 20
}
```
%% Output
0 1 2 (expected: 0, 1, 2)
10 11 20 (expected: 10, 11, 20)
%% Cell type:markdown id: tags:
These `enum` are placeholders for integers and might be used as such:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
enum color { red, green, blue } ;
int a { 5 };
color c = green;
int b = a + c;
std::cout << "b = " << b << " (expected: 6)" << std::endl;
enum shape { circle=10, square, triangle=20 };
shape s = triangle;
int d = s + c;
std::cout << "d = " << d << " (expected: 21... but we've just added a shape to a color without ado!)" << std::endl;
}
```
%% Output
b = 6 (expected: 6)
d = 21 (expected: 21... but we've just added a shape to a color without ado!)
%% Cell type:markdown id: tags:
A shortcoming of historical `enum ` is that the same word can't be used in two different `enum`:
%% Cell type:code id: tags:
``` C++17
{
enum is_positive { yes, no };
enum is_colored { yes, no }; // COMPILATION ERROR!
}
```
%% Output
input_line_13:5:23: error: redefinition of enumerator 'yes'
enum is_colored { yes, no }; // COMPILATION ERROR!
 ^
input_line_13:3:24: note: previous definition is here
enum is_positive { yes, no };
 ^
input_line_13:5:28: error: redefinition of enumerator 'no'
enum is_colored { yes, no }; // COMPILATION ERROR!
 ^
input_line_13:3:29: note: previous definition is here
enum is_positive { yes, no };
 ^

Interpreter Error:
%% Cell type:markdown id: tags:
### New enumerations
To overcome the two limitations we have just mentioned, C++11 makes it possible to declare new `enum class` enumerations, each constituting a separate type, not implicitly convertible into an integer. This type protects against previous errors at the cost of a little more writing work.
%% Cell type:code id: tags:
``` C++17
enum class is_positive { yes, no };
enum class is_colored { yes, no }; // OK
```
%% Cell type:code id: tags:
``` C++17
yes; // COMPILATION ERROR: `enum class ` value must be prefixed! (see below)
```
%% Output
input_line_16:2:2: error: use of undeclared identifier 'yes'
yes; // COMPILATION ERROR: `enum class ` value must be prefixed! (see below)
 ^

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
is_positive p = is_positive::yes; // OK
```
%% Cell type:code id: tags:
``` C++17
int is_positive_p = is_positive::no; // COMPILATION ERROR: not implicitly convertible into an integer
```
%% Output
input_line_18:2:6: error: cannot initialize a variable of type 'int' with an rvalue of type 'is_positive'
int is_positive_p = is_positive::no; // COMPILATION ERROR: not implicitly convertible into an integer
 ^ ~~~~~~~~~~~~~~~

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
is_positive::yes + is_colored::no; // COMPILATION ERROR: addition of two unrelated types
```
%% Output
input_line_19:2:19: error: invalid operands to binary expression ('is_positive' and 'is_colored')
is_positive::yes + is_colored::no; // COMPILATION ERROR: addition of two unrelated types
 ~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~

Interpreter Error:
%% Cell type:code id: tags:
``` C++17
{
enum class color { red, green, blue } ;
color c = color::green;
bool more_than_red = (c > color::red); // Both belong to the same type and therefore might be compared
}
```
%% Cell type:markdown id: tags:
## Numerical types
#### List of numerical types
The FORTRAN correspondences below are given as examples. The
size of the C++ digital types can vary depending on the processor used. The
standard C++ only imposes `short <= int <= long` and `float <= double <= long double`. This makes these predefined types unportable. Like many things
in C, and therefore in C++, performance is given priority over any other consideration.
The default integer and real types, `int` and `double`, are assumed
to match the size of the processor registers and be the fastest (for more details see [numerical types](http://en.cppreference.com/w/cpp/language/types))
| C++ | Fortran | Observations | 0 notation |
|:------------- |:---------:|:-------------------:|:----------:|
| `short` | INTEGER*2 | At least on 16 bits | None |
| `int` | INTEGER*4 | At least on 16 bits | 0 |
| `long` | INTEGER*8 | At least on 32 bits | 0l |
| `long long` | INTEGER*16| At least on 64 bits | 0ll |
| `float` | REAL*4 | - | 0.f |
| `double` | REAL*8 | - | 0. |
| `long double` | REAL*16 | - | 0.l |
All integer types (`short`, `int` and `long`) also have an unsigned variant, for example
`unsigned int`, which only takes positive values.
It should also be noted that the type `char` is the equivalent of one byte,
and depending on the context will be interpreted as a number or as a
character.
If you need an integer type of a defined size, regardless of the type of processor or platform used, you should use those already defined in `<cstdint>` for C++11 (for more details click [here](http://en.cppreference.com/w/cpp/types/integer)).
The _0 notation column_ is the way to notice explicitly the type in an expression; of course any value might be used instead of 0. A `u` might be used to signal the unsigned status for integer types; for instance `3ul` means 3 as an _unsigned long_. `auto` notation below will illustrate a case in which such a notation is useful.
#### Numeric limits
Always keep in mind the types of the computer don't match the abstract concept you may use in mathematics... The types stored especially don't go from minus infinity to infinity:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <limits> // for std::numeric_limits
{
std::cout << "int [min, max] = [" << std::numeric_limits<int>::min() << ", "
<< std::numeric_limits<int>::max() << "]" << std::endl;
std::cout << "unsigned int [min, max] = [" << std::numeric_limits<unsigned int>::min() << ", "
<< std::numeric_limits<unsigned int>::max() << "]" << std::endl;
std::cout << "short [min, max] = [" << std::numeric_limits<short>::min() << ", "
<< std::numeric_limits<short>::max() << "]" << std::endl;
std::cout << "float [min, max] = [" << std::numeric_limits<float>::min() << ", "
<< std::numeric_limits<float>::max() << "]" << std::endl;
std::cout << "double [min, max] = [" << std::numeric_limits<double>::min() << ", "
<< std::numeric_limits<double>::max() << "]" << std::endl;
std::cout << "long double [min, max] = [" << std::numeric_limits<long double>::min() << ", "
<< std::numeric_limits<long double>::max() << "]" << std::endl;
}
```
%% Output
int [min, max] = [-2147483648, 2147483647]
unsigned int [min, max] = [0, 4294967295]
short [min, max] = [-32768, 32767]
float [min, max] = [1.17549e-38, 3.40282e+38]
double [min, max] = [2.22507e-308, 1.79769e+308]
long double [min, max] = [3.3621e-4932, 1.18973e+4932]
%% Cell type:markdown id: tags:
If an initial value is not in the range, the compiler will yell:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
{
short s = -33010; // triggers a warning: outside the range
std::cout << s << std::endl;
}
```
%% Output
input_line_28:3:15: warning: implicit conversion from 'int' to 'short' changes value from -33010 to 32526 [-Wconstant-conversion]
short s = -33010; // triggers a warning: outside the range
 ~ ^~~~~~

32526
%% Cell type:markdown id: tags:
However, if you go beyond the numeric limit during a computation you're on your own:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <limits> // for std::numeric_limits
{
unsigned int max = std::numeric_limits<unsigned int>::max();
std::cout << "Max = " << max << std::endl;
std::cout << "Max + 1 = " << max + 1 << "!" << std::endl;
}
```
%% Output
Max = 4294967295
Max + 1 = 0!
%% Cell type:markdown id: tags:
When you reach the end of a type, a modulo is actually applied to make put it back into the range!
Don't worry, for most computations you shouldn't run into this kind of trouble, but if you are dealing with important values it is important to keep in mind this kind of issues.
The most obvious way to avoid this is to choose appropriate types: if your integer might be huge a `long` is more appropriate than an `int`.
Other languages such as Python gets a underlying integer model that is resilient to this kind of issue but there is a cost behind; types such as those used in C++ are tailored to favor optimization on your hardware.
%% Cell type:markdown id: tags:
#### Conversions between digital types
In C++11, there is a difference in compiler behavior between initialization and assignment. Accuracy losses are allowed during an assignment, but not during an initialization between braces:
%% Cell type:code id: tags:
``` C++17
{
float f = 1.12345678901234567890;
double d = 2.12345678901234567890;
float f_d(d);
float f_dd = d;
}
```
%% Cell type:markdown id: tags:
are ok while the operation below doesn't compile:
%% Cell type:code id: tags:
``` C++17
{
double d = 2.12345678901234567890;
float f_d{d};
}
```
%% Cell type:markdown id: tags:
Accuracy losses are detected during conversion:
* from a floating point type (`long double`, `double` and `float`) into an integer type.
* from a `long double` into a `double` or a `float`, unless the source is constant and its value will fit into the type of the destination
* from a `double` into a `float`, unless the source is constant and its value will fit in the type of the destination
* from an integer type to an enumerated or floating point type, unless the source is constant and its value will fit into the type of the destination
* from an integer type to an enumerated type or another integer type, unless the source is constant and its value will fit into the type of the destination
%% Cell type:markdown id: tags:
### Explicit conversions inherited from C
In the case of an explicit conversion, the programmer explicitly says which conversion to use.
C++ inherits the forcing mechanism of the C type:
%% Cell type:code id: tags:
``` C++17
{
unsigned short i = 42000 ;
short j = short(i) ;
unsigned short k = (unsigned short)(j) ;
}
```
%% Cell type:markdown id: tags:
It is **not recommended** to use this type of conversion: even if it is clearly faster to type, it is less accurate and does not stand out clearly when reading a code; it is preferable to use the other conversion modes mentioned below.
%% Cell type:markdown id: tags:
### Explicit conversions by static_cast
C++ has also redefined a family of type forcing,
more verbose but more precise. The most common type of explicit conversion is the `static_cast`:
%% Cell type:code id: tags:
``` C++17
{
unsigned short i = 42000;
short j = static_cast<short>(i);
unsigned short k = static_cast<unsigned short>(j);
}
```
%% Cell type:markdown id: tags:
Another advantage of this more verbosy syntax is that you may find it more easily in your code with your editor search functionality.
%% Cell type:markdown id: tags:
### Other explicit conversions
There are 3 other types of C++ conversions:
* const_cast, to add or remove constness to a reference or a pointer.
* dynamic_cast, which will be introduced when we'll deal with polymorphism.
* reinterpret_cast, which is a very brutal cast which changes the type into any other type, regardless of the compatibility of the two types considered. It is a dangerous one that should be considered only in very last resort (usually when interacting with a C library).
%% Cell type:markdown id: tags:
## Characters and strings
### Historical strings
In C, a character string is literally an array of `char` variables, the last character of which is by convention the symbol `\0`.
The `strlen` function returns the length of a string, which is the number of characters between the very first character and the first occurrence of `\0`.
The `strcpy` function copies a character string to a new memory location; care must be taken to ensure that the destination is large enough to avoid any undefined behavior.
The `strncpy` function allows you to copy only the first <b>n</b> first characters, where <b>n</b> is the third parameter of the function. Same remark about the need to foresee a large enough destination.
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <cstring> // For strlen, strcpy, strncpy
{
char bonjour[] = {'b','o','n','j','o','u','r','\0'};
char coucou[] = "coucou";
char* salut = "salut"; // To avoid in C++ (see warning)
char copie[10] = {0}; // = {'\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'};
strcpy(copie, bonjour);
std::cout << "String '" << copie << "' is " << strlen(copie) << " characters long." << std::endl;
strncpy(copie, coucou, strlen(coucou));
copie[strlen(coucou)] = '\0'; // Don't forget to terminate the string!
std::cout << "String '" << copie << "' is " << strlen(copie) << " characters long." << std::endl;
}
```
%% Output
input_line_34:5:19: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings]
char* salut = "salut"; // To avoid in C++ (see warning)
 ^

String 'bonjour' is 7 characters long.
String 'coucou' is 6 characters long.
%% Cell type:markdown id: tags:
There are a lot of features to work from historical strings. For more information, do not hesitate to consult [this reference page](http://www.cplusplus.com/reference/cstring/).
%% Cell type:markdown id: tags:
### std::string
In modern C++, rather than bothering with character tables
which come from the C language, it's easier to use the type `std::string`, provided
through the standard language library:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <cstring> // For strlen
#include <string> // For std::string
{
const char* bonjour_str = "bonjour";
std::string bonjour = bonjour_str;
std::string salut("salut");
std::string coucou {"coucou"};
std::string copie {};
copie = bonjour;
std::cout << "String '" << copie << "' is " << copie.length() << " characters long." << std::endl;
copie = coucou; // please notice affectation is much more straightforward
std::cout << "String '" << copie << "' is " << copie.length() << " characters long." << std::endl;
const char* copie_str = bonjour.data(); // Returns a classic C-string (from C++11 onward)
const char* old_copy_str = &bonjour[0]; // Same before C++11...
std::cout << "String '" << copie_str << "' is " << strlen(copie_str) << " characters long." << std::endl;
std::string dynamique {"dynamic std::string"};
std::cout << "String '" << dynamique << "' is " << dynamique.length() << " characters long." << std::endl;
dynamique = "std::string is dynamical and flexible";
std::cout << "String '" << dynamique << "' is " << dynamique.length() << " characters long." << std::endl;
}
```
%% Output
String 'bonjour' is 7 characters long.
String 'coucou' is 6 characters long.
String 'bonjour' is 7 characters long.
String 'dynamic std::string' is 19 characters long.
String 'std::string is dynamical and flexible' is 37 characters long.
%% Cell type:markdown id: tags:
Please notice C++17 introduced [std::string_view](https://en.cppreference.com/w/cpp/header/string_view) which is more efficient than `std::string` for some operations; it is however out of the scope of this tutorial.
%% Cell type:markdown id: tags:
## Renaming types
Sometimes it may be handy to rename a type, for instance if you want to be able to change easily throughout the code the numeric precision to use. Historical syntax (up to C++ 11 and still valid) was `typedef`:
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <iomanip> // For std::setprecision
{
typedef double real; // notice the ordering: new typename comes after its value
real radius {1.};
real area = 3.1415926535897932385 * radius * radius;
std::cout <<"Area = " << std::setprecision(15) << area << std::endl;
}
```
%% Cell type:markdown id: tags:
In more modern C++ (C++11 and above), another syntax relying on `using` keyword was introduced; it is advised to use it as this syntax is more powerful in some contexts (see later with templates...)
%% Cell type:code id: tags:
``` C++17
#include <iostream>
#include <iomanip> // For std::setprecision
{
using real = float; // notice the ordering: more in line with was we're accustomed to when
// initialising variables.
real radius {1.};
real area = 3.1415926535897932385 * radius * radius;
std::cout <<"Area = " << std::setprecision(15) << area << std::endl;
}
```
%% Cell type:markdown id: tags:
## `decltype` and `auto`
C++ 11 introduced new keywords that are very handy to deal with types:
* `decltype` which is able to determine at compile time the underlying type of a variable.
* `auto` which determines automatically the type of an expression.
%% Cell type:code id: tags:
``` C++17
#include <vector>
{
auto i = 5; // i is here an int.
auto j = 5u; // j is an unsigned int
decltype(j) k; // decltype(j) is interpreted by the compiler as an unsigned int.
}
```
%% Cell type:markdown id: tags:
On such trivial examples it might not seem much, but in practice it might prove incredibly useful. Consider for instance the following C++03 code (the details don't matter: we'll deal with `std::vector` in a [later notebook](/notebooks/5-UsefulConceptsAndSTL/3-Containers.ipynb)):
%% Cell type:code id: tags:
``` C++17
#include <vector>
#include <iostream>
{
std::vector<unsigned int> primes { 2, 3, 5, 7, 11, 13, 17, 19 }; // I'm cheating: it's C++ 11 notation...
// In C++ 03 you would have to push_back one by one each of the element!
for (std::vector<unsigned int>::const_iterator it = primes.cbegin();
it != primes.cend();
++it)
{
std::cout << *it << " is prime." << std::endl;
}
}
```
%% Output
2 is prime.
3 is prime.
5 is prime.
7 is prime.
11 is prime.
13 is prime.
17 is prime.
19 is prime.
%% Cell type:markdown id: tags:
It's very verbosy; we could of course use alias:
%% Cell type:code id: tags:
``` C++17
#include <vector>
#include <iostream>
{
std::vector<unsigned int> primes { 2, 3, 5, 7, 11, 13, 17, 19 }; // I'm cheating: it's C++ 11 notation...
using iterator = std::vector<unsigned int>::const_iterator;
for (iterator it = primes.cbegin();
it != primes.cend();
++it)
{
std::cout << *it << " is prime." << std::endl;
}
}
```
%% Output
2 is prime.
3 is prime.
5 is prime.
7 is prime.
11 is prime.
13 is prime.
17 is prime.
19 is prime.
%% Cell type:markdown id: tags:
But with `decltype` we may write instead:
%% Cell type:code id: tags:
``` C++17
#include <vector>
#include <iostream>
{
std::vector<unsigned int> primes { 2, 3, 5, 7, 11, 13, 17, 19 }; // I'm cheating: it's C++ 11 notation...
for (decltype(primes.cbegin()) it = primes.cbegin();
it != primes.cend();
++it)
{
std::cout << *it << " is prime." << std::endl;
}
}
```
%% Output
2 is prime.
3 is prime.
5 is prime.
7 is prime.
11 is prime.
13 is prime.
17 is prime.
19 is prime.
%% Cell type:markdown id: tags:
or even better:
%% Cell type:code id: tags:
``` C++17
#include <vector>
#include <iostream>
{
std::vector<unsigned int> primes { 2, 3, 5, 7, 11, 13, 17, 19 }; // I'm cheating: it's C++ 11 notation...
for (auto it = primes.cbegin();
it != primes.cend();
++it)
{
std::cout << *it << " is prime." << std::endl;
}
}
```
%% Output
2 is prime.
3 is prime.
5 is prime.
7 is prime.
11 is prime.
13 is prime.
17 is prime.
19 is prime.
%% Cell type:markdown id: tags:
That is not to say `decltype` is always inferior to `auto`: there are some cases in which decltype is invaluable (especially in metaprogramming - but it's out os scope of this tutorial!).
C++ 14 introduced a new one (poorly) called `decltype(auto)` which usefulness will be explained below:
%% Cell type:code id: tags:
``` C++17
#include <algorithm>