Study notes: Initiation à la programmation
| updated
Notes from the edX course Initiation à la programmation
Contents
Basis of programming: operations + data
operations:
- expressions
- operators
- control structures
- functions
data:
- variables:
- identifier, type, location in memory storing value
- data containers:
- strings
- arrays: dynamic, static
- structs
Variables
Uninitialised variables have undefined value, e.g. in int x;
, x ≠ 0.
Assigning a double to an int truncates it silently.
Values of expressions
Assignment
The effect of a =
expression is assignment,
but its value is the value of the rval (what value gets assigned).
Thus e.g. i = j = 3;
means i = (j = 3);
,
which has the same effect as j = 3; i = 3;
.
Better not to use the value though: this construct mixes side effect and eval/return.
Incrementing
Effect of i++;
is identical to ++i;
, but the value differs:
j = i++;
assigns the value before incrementing to j,j = ++i;
increments i and then assigns the new value to j, i.e.j == i
.
This difference is only noticeable if you use the value somehow (as opposed to the effect). Better not to anyway, since the expression then has both an effect and side effect.
Always use the ++i
form:
++i;
==i = i + 1;
because the value of both statements is the new value of i.++i
can be implemented without copying data, whereasi++
always copies. (This only matters in languages allowing the operator to be implemented on custom types, since primitive types are always copied anyway.)
Initialisation
Init by copy
int x = 1;
Direct init
int x(1);
- single operation (conceptually);
- same syntax as for object constructors;
- probably more efficient?
Newer syntax
int x{1};
- recommended by Stroustrup;
- risk of confusion with rval for a collection, e.g.
vec xs = {1, 2};
? Therefore discouraged in this course.
Numeric sizes
See limits.h
to check limits on given compiler/arch combination:
limits::numeric_limits<int>::max()
- int
- long int == long
- short int == short
The above can all be prefixed with unsigned
.
- float
- double
- long double
‘const’ vs. ‘constexpr’
const int i(1);
does not mean the value in memory is constant,
since it can still be modified by assigning a new value via a pointer to i
.
But not via the name i
: i
is read-only.
Variables declared as const
need not be known at compile time;
it can be initialised from user input, e.g. int read; cin >> read; const int i (read);
,
to signal that i
will not be modified later on.
constexpr
(variable or expression) means constant and must be known at compile time,
e.g. constexpr double pi (3.1415);
.
Use this one whenever conditions are met.
Control structures
- conditional branches
- iteration
- conditional loops
Be careful not to use assignment in the condition, e.g. if (x = 1) { }
:
assignment has a value (coerced to bool).
- Logical operator
and
is equivalent to&&
. Similarlyor
==||
, andnot
==!
. - The bit-wise versions are:
& | ~
. - learncpp.com says they are equivalent, but that experienced devs are more likely to use the symbolic than the verbal forms.
Lazy evaluation of chained logical expressions (same as in Python):
e.g. (i != 0) and (25/i > 12)
is safe, since 25/i
is not evaluated if i == 0
.
‘switch’ as alternative to if-else chains
switch (expr) {
case 1: stmt 1; break;
case 2:
case 3: stmt 2; break;
default: stmt;
}
- The
expr
must evaluate to an int (i.e. bool, enum, char are ok). - Cases must be constexpr.
break;
required to prevent fall-through.- Empty statement (without break) can be used to group cases (e.g. 2 || 3 above).
- Default case is executed if no previous matches (or matches missing break) encountered.
Note: compiler does not check for non-exhaustive matches!
‘for’ loops
for (int i(0) ; i < 5 ; ++i ) { ... }
// decl+init cond incr body
i
is only in scope until the end of the loop.
Since C++ 11:
for (auto x : xs) { ... }
to iterate over elements in a collection.
‘while’ loops
Run body one or more times:
do {
cout << "Provide n > 0";
cin >> n;
} while (n <= 0);
Run body 0 or more times (none if cond is initially false):
while (n < 10) {
++n;
}
Use:
for
loop if number of iterations is known in advance;do-while
loop if unknown but e.g. looking to constrain input to a range;while
loop otherwise.
Variable scope
Until the end of the block in which it was declared –
except for globals declared even outside main()
.
Can mask other variables of the same name with broader scope. Better to choose a different name, though, and to limit scope.