You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: intro.md
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,19 +2,19 @@
2
2
3
3
Welcome to a short primer on using the C & C++ programming languages. These notes were written for students on the ACSE and EDSML Masters courses in the Earth Science & Engineering Department at Imperial College London.
4
4
5
-
These notes assume some previous programming experience in Python, equivalent to that of the Modern Programming Methods course, however they should be possible for anyone with previous experience coding in an interpretted language.
5
+
These notes assume some previous programming experience in Python, equivalent to that of the Modern Programming Methods or Numerical Programming in Python courses, however they should be possible for anyone with previous experience coding in an interpretted language.
6
6
7
7
This primer combines some notes introducing C-like languages to novice users, along with some exercises to practise your new knowledge. It is split into three sections, It will probably take a maximum of 16 hours to work through, depending on your previous knowledge and how far you go with the exercises.
8
8
9
9
## Why do we teach C++?
10
10
11
-
Python code is relatively easy to run (although not always easy to write), but doesn't always run very quickly. By using a compiled language like C++ we can get "closer to the metal" of the computer processor and write code which generates a solution much faster (sometimes hundreds or thousands of times faster). Often this performance difference doesn't matter, and the time taken to develop & maintain the code is more important, but for certain large scale calculation, which can take hours or days to run, then these differences become important.
11
+
Python code is relatively easy to run (although not always easy to write), but doesn't always run very quickly. By using a compiled language like C++ we can get "closer to the metal" of the computer processor and write code which generates a solution much faster (sometimes hundreds or thousands of times faster). Often this performance difference doesn't matter, and the time taken to develop & maintain the code is more important, but for certain large scale calculations, which can take hours or days to run, then these differences become important.
12
12
13
13
There are many other compiled languages in existence (eg. Fortran, Java, C#, ...) but C and C++ are currently some of the most widely used, and in demand. Unlike niche scientific languages such as Fortran, they are used both for numerical and systems programming and many modern machine learning frameworks have a C or C++ interface.
14
14
15
15
## How does C/C++ differ from Python?
16
16
17
-
Python is what is known as an interpreted language. To run code, you point a single program, the interpreter at your source file, and it translates and runs the instructions in a way your computer can understand. C & C++ are compiled languages. A tool called a compiler is used to convert your human-readable source files into an executable instruction file your machine understands. This file can then be run many times.
17
+
Python is what is known as an interpreted language. To run code, you point a single program, the interpreter, at your source file, and it translates and runs the instructions in a way your computer can understand. C & C++ are compiled languages. A tool called a compiler is used to convert your human-readable source files into an executable instruction file your machine understands. This file can then be run many times.
18
18
19
19
Python is also a garbage-collected language. It cleans up (eventually) all the memory you use to hold variables in your programs, once it realises you're no longer interested in them. C-like languages give you, as a programmer, more power & control on where in your computer memory things live, and how long they stay around for. In return, it is often the programmer's job to clean up once you have finished
Copy file name to clipboardExpand all lines: part_one/01_running.md
+17-9Lines changed: 17 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -27,7 +27,7 @@ A more local option is to take advantage of the combined power of Docker and Vis
27
27
28
28
To begin, fork the accompanying [examples repository](https://github.com/ese-msc/c-examples) and download it, then with Docker desktop running, open your local repository in VS code. You will be presented with a query banner "Folder contains a Dev Container configuration file. Reopen folder to develop in a container (learn more).". Select "Reopen in Container". This will restart the VS Code editor window, while connecting to a Docker container build from the repository [C examples Dockerfile](https://ese-msc/c-examples/.devcontainer/Dockerfile). This container has `git` and `Python` installed, together a working linux C++ compiler (the GNU compiler) and some useful VS Code extensions installed.
29
29
30
-
For simple non-interactive C++ files, you can now build & run them with the Run Code button (ctrl+alt+N). For interactive files, you will need to run the program yourself using (for a file `hello.cpp`in the current directory) a command like
30
+
For simple non-interactive C++ files, you can now build & run them with the Run Code button (ctrl+alt+N). For interactive files, you will need to run the program yourself using (for a file `hello.cpp`in the current directory) a command like:
31
31
32
32
```
33
33
g++ -o hello hello.cpp
@@ -56,7 +56,7 @@ Mac users have a number of routes to set up their system for C++. We recommend t
56
56
57
57
The open source third-party mac package manager [Homebrew](https://brew.sh/) provides preconfigured versions of a number of unix-like packages, including versions of the GNU C/C++ compilers.
58
58
59
-
Most Mac users on th course will already have Homebrew installed, but for those that don'tapplication itself can be downloaded using the script & instructions from the Homebrew homepage. Additional (and alternative) instructions can be found [here](https://docs.brew.sh/Installation). Once this installation is complete, running the command
59
+
Most Mac users on the course will already have Homebrew installed, but for those that don't, the application itself can be downloaded using the script & instructions from the Homebrew homepage. Additional (and alternative) instructions can be found [here](https://docs.brew.sh/Installation). Once this installation is complete, running the command:
60
60
61
61
```
62
62
brew install gcc
@@ -71,15 +71,16 @@ gcc-13 --version
71
71
You should see a response something like
72
72
73
73
```
74
-
gcc-12 (Homebrew GCC 13.2.0) 13.2.0
74
+
gcc-13 (Homebrew GCC 13.2.0) 13.2.0
75
75
Copyright (C) 2023 Free Software Foundation, Inc.
76
-
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
76
+
This is free software; see the source for copying conditions. There is NO
77
+
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
77
78
```
78
79
79
80
To compile a C++ file called `hello.cpp` into an exectuable called `hello`, then run it, use a command like
Copy file name to clipboardExpand all lines: part_one/02_hello_world.md
+2-2Lines changed: 2 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,7 +2,7 @@
2
2
3
3
## Introduction
4
4
5
-
Now that you hopefully have access to a working compiler, and a place to writewe'll move on to giving you some practical code to compile. A common first program for people to code in a new programming language is to write just enough code to print the phrase "Hello World!" to the screen (or other output device) and then exit.
5
+
Now that you hopefully have access to a working compiler, and a place to write, we'll move on to giving you some practical code to compile. A common first program for people to code in a new programming language is to write just enough code to print the phrase "Hello World!" to the screen (or other output device) and then exit.
6
6
7
7
The popularity of this tradition actually dates back to the beginnings of the C programming language in 1978 and the book "The C Programming Language" by Brian Kernighan and Dennis Ritchie.
8
8
@@ -34,7 +34,7 @@ _hello.c_:
34
34
35
35
Unlike Python, we need to use a function from outside the core language, in this case the function `printf` from the standard library `stdio`, in order to print our message to screen. At the compilation stage we do this with command `#include`, a C preprocessor directive, which in practice works very similarly to the `import` statement in Python by pulling other code into our work.
36
36
37
-
Where Python runs through commands beginning at the top of a script file, in `C` programs (at least, those printing to screen in the terminal) start at the beginning of the special `main` function. This function usually returns an integer, where `0` is taken to mean that things worked successfully, while other values are generally taken as a sign that something went wrong.
37
+
Where Python runs through commands beginning at the top of a script file, C programs (at least, those printing to screen in the terminal) start at the beginning of the special `main` function. This function usually returns an integer, where `0` is taken to mean that things worked successfully, while other values are generally taken as a sign that something went wrong.
38
38
39
39
Finally, in C/C++ we **must** use the double quotes `"` to indicate a string (the `'` character won't work, and is only used with single characters), and since the `printf` function doesn't end lines automatically, we must do it ourselves using the special end-of-line `\n` "escape" character.
Copy file name to clipboardExpand all lines: part_one/03_simple_math.md
+1-2Lines changed: 1 addition & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -133,7 +133,7 @@ int main(void){
133
133
134
134
Note that unlike in Python, plotting in C++ is hard work, so we're just printing the values to screen instead.
135
135
136
-
### Quadrature
136
+
## Quadrature
137
137
138
138
Now we'll implement two quadrature methods, the midpoint and the trapezium rules. We'll start with the Python code (see the Computational Mathematics course for the annotated versions):
Copy file name to clipboardExpand all lines: part_one/04_input-output.md
+9-7Lines changed: 9 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,8 @@
1
-
##Programs with input
1
+
# Programs with input
2
2
3
3
Since C++ programmes are compiled, we don't have the same flexibility to change the behaviour of the program at runtime as we do with Python. However, we can still take input data from the user in a number of ways.
4
4
5
-
###Taking input from the keyboard
5
+
## Taking input from the keyboard
6
6
7
7
The counterpart to `std::cout` is `std::cin`. It's usage is similar but "in the other direction". For example:
8
8
@@ -51,15 +51,15 @@ int main(){
51
51
}
52
52
```
53
53
54
-
###Taking input straight from the command line
54
+
## Taking input straight from the command line
55
55
56
56
As we saw with Python, another useful way to pass information into a program is on the command line. So far we have always used `main` functions with no input, but a longer form of the input signature is
57
57
58
58
```
59
59
int main(int argc, char* argv[])
60
60
```
61
61
62
-
Here we have two variables which are automatically assigned by the operating system, the integer `argc`, and an array of strings, `argv`. Just like with the Python `sys.argv`, the array is populated with a space separated list of the command line arguments used to call the program, with the first entry (`argv[0]`) equal to the name used to set the program running.
62
+
Here we have two variables which are automatically assigned by the operating system, the integer `argc` (the number of arguments), and an array of strings, `argv`. Just like with the Python `sys.argv`, the array is populated with a space separated list of the command line arguments used to call the program, with the first entry (`argv[0]`) equal to the name used to set the program running.
63
63
64
64
```c++
65
65
#include<iostream>
@@ -77,11 +77,13 @@ int main(int argc, char* argv[]){
77
77
}
78
78
```
79
79
80
-
### Taking input from files
80
+
Note that here we use the `atof` function to convert the string to a floating point number. We also have to be careful to start our loop at `i=1` since the first entry in the array is the name of the program itself.
81
+
82
+
## Taking input from files
81
83
82
84
The last useful way we'll talk about to pass information in to a program is via a file. This is more involved than the previous versions, so don't be too worried if you don't follow all the details.
83
85
84
-
As with input/output the standard methods differ somewhat between C & C++. In C we use a collection of functions from `stdio.h`. For example to write a file:
86
+
As with input/output, the standard methods differ somewhat between C & C++. In C we use a collection of functions from `stdio.h`. For example to write a file:
85
87
86
88
```c
87
89
#include <stdio.h>
@@ -134,7 +136,7 @@ or
134
136
```c++
135
137
int num;
136
138
fs.open ("example.txt", std::fstream::in);
137
-
/* read an int from example.txt (which is assumed)
Copy file name to clipboardExpand all lines: part_three/01_pointers.md
+20-22Lines changed: 20 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -15,7 +15,7 @@ print(a)
15
15
```
16
16
Running the above code in the Python interpretter gives the output `[1]`. This is because the names `a` and `b` have both been bound to the same list object, and updating the list via one name updates it via the other. C and C++ allow similar behaviour usuing a concept called "pointer"s.
17
17
18
-
A C style pointer holds a location (usually called an address) in you computer's memory, along with an attached data type. This address can be looked up ("dereferenced") to get hold of the underlying value to:
18
+
A C style pointer holds a location (usually called an address) in your computer's memory, along with an attached data type. This address can be looked up ("dereferenced") to get hold of the underlying value to:
19
19
1. use in an expression
20
20
2. update via an assignment.
21
21
@@ -28,26 +28,26 @@ As a C/C++ variable, a pointer must be declared the first time it is used. The s
28
28
int *a; // This is a pointer to an int
29
29
```
30
30
31
-
When declared this way, `a` holds a memory location (written as a number of a fixed size, usually 64 bits on modern comuputer systems). To actually make it "point" to a "target" we need the memory address of a suitable integer. The language has an operator, `&`, which will get this for us. To dereference (i.e. look up the value)`a` points to, we use the derferencing operator `*`. To assign a new value to the target, we assign it to the dereferenced object, that is `*a`. Let's look at a short C++ program which exercises all this new behaviour
31
+
When declared this way, `a` holds a memory location (written as a number of a fixed size, usually 64 bits on modern comuputer systems). To actually make it "point" to a "target" we need the memory address of a suitable integer. The language has an operator, `&`, which will get this for us. To dereference (i.e. look up) the value `a` points to, we use the derferencing operator `*`. To assign a new value to the target, we assign it to the dereferenced object, that is `*a`. Let's look at a short C++ program which exercises all this new behaviour
32
32
33
33
```c++
34
34
#include<iostream>
35
35
36
36
intmain(){
37
-
int *a;
38
-
int b = 7; // B is a normal int variable holding the value 7
39
-
a = &b; // point
37
+
int *a;
38
+
int b = 7; // B is a normal int variable holding the value 7
39
+
a = &b; // point
40
40
41
-
std::cout << a << std::endl;; // returns b's memory address.
This embeds a lot of new concepts in one go, so feel free to run this one a few tips and check you've got to grips with the new behaviour.
50
+
This embeds a lot of new concepts in one go, so feel free to run this one a few times and check you've got to grips with the new behaviour.
51
51
52
52
If you think back, we've already seen the `*` operator a few times, and the `&` operator at least once. In particular, `&` is used in C++ to indicate "pass by reference" since it's already the C reference operator. To pass by reference in C we must declare the input arguments as pointers and pass in the *value* of a reference to the object we care about by using the `&` operator.
53
53
@@ -57,21 +57,19 @@ Another place the * operator has turned up is when passing 2D arrays into functi
57
57
58
58
```c++
59
59
/* swap two elements (array version) */
60
-
int[2] swap2(int a[]){
61
-
out[2];
62
-
out[0] = a[1];
63
-
out[1] = a[0] ;
64
-
return out;
60
+
voidswap2(int a[]){
61
+
int tmp = a[0];
62
+
a[0] = a[1];
63
+
a[1] = tmp;
65
64
}
66
65
```
67
66
and
68
67
```c++
69
68
/* swap two elements (pointer version)*/
70
-
int[2] swap2(int *a){
71
-
out[2];
72
-
out[0] = a[1];
73
-
out[1] = a[0] ;
74
-
return out;
69
+
void swap2(int *a){
70
+
int tmp = a[0];
71
+
a[0] = a[1];
72
+
a[1] = tmp;
75
73
}
76
74
```
77
75
@@ -174,7 +172,7 @@ We didn't need any extra libraries this time, since `new` and `delete` are baked
174
172
175
173
### Additional pointer types
176
174
177
-
In C++, traditional pointers are now considered less useful and alternative constructs such as "smart pointers" (which clean themselves up when they pass out of scope) and unique pointers (which prevent multiple pointers all being directed at the same target) are in greater use. You will learn more about these techniques during the rest of the course.
175
+
In C++, traditional pointers are now considered less useful and alternative constructs such as "smart pointers" (which clean themselves up when they pass out of scope) and unique pointers (which prevent multiple pointers all being directed at the same target) are in greater use. You will learn more about these techniques during the rest of the Advanced Programming course.
0 commit comments