Skip to content

Commit b39ba84

Browse files
authored
Merge pull request #2 from ese-msc-confidential/tmd_updates
tmd updates
2 parents ea7f3ff + a8b4fcf commit b39ba84

File tree

13 files changed

+98
-74
lines changed

13 files changed

+98
-74
lines changed

_toc.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ sections:
66
- file: part_one/01_running
77
- file: part_one/02_hello_world
88
- file: part_one/03_simple_math
9-
- file: part_one/04_troubleshooting
9+
- file: part_one/04_input-output.md
10+
- file: part_one/05_troubleshooting
1011
- file: part_one/exercises_one
1112
- file: part_two/intro
1213
sections:
@@ -21,12 +22,12 @@ sections:
2122
- file: part_three/02_structs
2223
- file: part_three/03_header_files
2324
- file: part_three/04_build_systems
25+
- file: part_three/05_combining_with_python.md
2426
- file: part_three/exercises_three
2527
- file: appendices/intro
2628
sections:
2729
- file: appendices/keywords
2830
- file: appendices/c-preprocessor
29-
- file: appendices/combining_with_python
3031
- file: changelog
3132
- file: genindex
3233
title: Index

intro.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,19 @@
22

33
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.
44

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.
66

77
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.
88

99
## Why do we teach C++?
1010

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.
1212

1313
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.
1414

1515
## How does C/C++ differ from Python?
1616

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.
1818

1919
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
2020

part_one/01_running.md

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ A more local option is to take advantage of the combined power of Docker and Vis
2727

2828
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.
2929

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:
3131

3232
```
3333
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
5656

5757
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.
5858

59-
Most Mac users on th course will already have Homebrew installed, but for those that don't 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
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:
6060

6161
```
6262
brew install gcc
@@ -71,15 +71,16 @@ gcc-13 --version
7171
You should see a response something like
7272

7373
```
74-
gcc-12 (Homebrew GCC 13.2.0) 13.2.0
74+
gcc-13 (Homebrew GCC 13.2.0) 13.2.0
7575
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.
7778
```
7879

7980
To compile a C++ file called `hello.cpp` into an exectuable called `hello`, then run it, use a command like
8081

8182
```
82-
g++-12 -o hello hello.cpp
83+
g++-13 -o hello hello.cpp
8384
./hello
8485
```
8586

@@ -100,12 +101,12 @@ cc --version
100101
You should see a response something like
101102

102103
```
103-
Apple clang version 12.0.5 (clang-1205.0.22.11)
104-
Target: arm64-apple-darwin20.3.0
104+
Apple clang version 14.0.0 (clang-1400.0.29.202)
105+
Target: arm64-apple-darwin21.6.0
105106
Thread model: posix
106-
InstalledDir: /Applications/Xcode.app/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
107+
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
107108
```
108-
althought the precise values may be a little different.
109+
although the precise values may be a little different.
109110

110111
To compile a C++ file called `hello.cpp` into an exectuable called `hello`, then run it, use a command like
111112

@@ -135,6 +136,13 @@ gcc --version
135136

136137
You should see a response something like
137138

139+
```
140+
gcc (Ubuntu 11.4.0-1unintu1~22.04) 11.4.0
141+
Copyright (C) 2021 Free Software Foundation, Inc.
142+
This is free software; see the source for copying conditions. There is NO
143+
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
144+
```
145+
138146
To compile a C++ file called `hello.cpp` into an exectuable called `hello`, then run it, use a command like
139147

140148
```

part_one/02_hello_world.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
## Introduction
44

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.
66

77
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.
88

@@ -34,7 +34,7 @@ _hello.c_:
3434
3535
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.
3636
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.
3838
3939
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.
4040

part_one/03_simple_math.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ int main(void){
133133
134134
Note that unlike in Python, plotting in C++ is hard work, so we're just printing the values to screen instead.
135135
136-
### Quadrature
136+
## Quadrature
137137
138138
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):
139139
@@ -153,7 +153,6 @@ def midpoint_rule(a, b, func, number_intervals=10):
153153
return I_M
154154
155155
def trapezium_rule(a, b, func, number_intervals=10):
156-
157156
interval_size = (b - a)/number_intervals
158157
159158
I_T = 0.0

part_one/04_input-output.md

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
## Programs with input
1+
# Programs with input
22

33
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.
44

5-
### Taking input from the keyboard
5+
## Taking input from the keyboard
66

77
The counterpart to `std::cout` is `std::cin`. It's usage is similar but "in the other direction". For example:
88

@@ -51,15 +51,15 @@ int main(){
5151
}
5252
```
5353

54-
### Taking input straight from the command line
54+
## Taking input straight from the command line
5555

5656
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
5757

5858
```
5959
int main(int argc, char* argv[])
6060
```
6161

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.
6363

6464
```c++
6565
#include <iostream>
@@ -77,11 +77,13 @@ int main(int argc, char* argv[]){
7777
}
7878
```
7979
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
8183
8284
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.
8385
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:
8587
8688
```c
8789
#include <stdio.h>
@@ -134,7 +136,7 @@ or
134136
```c++
135137
int num;
136138
fs.open ("example.txt", std::fstream::in);
137-
/* read an int from example.txt (which is assumed)
139+
/* read an int from example.txt, which is assumed
138140
to exist already. Unlike Python, we need to write
139141
additional code if that might not be true.*/
140142
fs >> num;

part_three/01_pointers.md

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ print(a)
1515
```
1616
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.
1717

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:
1919
1. use in an expression
2020
2. update via an assignment.
2121

@@ -28,26 +28,26 @@ As a C/C++ variable, a pointer must be declared the first time it is used. The s
2828
int *a; // This is a pointer to an int
2929
```
3030

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
3232

3333
```c++
3434
#include <iostream>
3535

3636
int main(){
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
4040

41-
std::cout << a << std::endl;; // returns b's memory address.
42-
std::cout << *a << std::endl; // returns b's value (i.e. 7).
41+
std::cout << a << std::endl;; // returns b's memory address.
42+
std::cout << *a << std::endl; // returns b's value (i.e. 7).
4343

44-
*a = 10; // updates a's target
45-
std::cout << b << std::endl; // returns 10
46-
return 1;
44+
*a = 10; // updates a's target
45+
std::cout << b << std::endl; // returns 10
46+
return 1;
4747
}
4848
```
4949

50-
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.
5151

5252
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.
5353

@@ -57,21 +57,19 @@ Another place the * operator has turned up is when passing 2D arrays into functi
5757

5858
```c++
5959
/* 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+
void swap2(int a[]){
61+
int tmp = a[0];
62+
a[0] = a[1];
63+
a[1] = tmp;
6564
}
6665
```
6766
and
6867
```c++
6968
/* 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;
7573
}
7674
```
7775

@@ -174,7 +172,7 @@ We didn't need any extra libraries this time, since `new` and `delete` are baked
174172

175173
### Additional pointer types
176174

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.
178176

179177
## Summary
180178

0 commit comments

Comments
 (0)