Type System Basics Type System Basics Type Basics
Type const variable_name = value;
- value can't be changed once assigned
- initial value can be dynamic (= set at runtime)
int i = 0;
cin >> i;
int const k = i; // "int constant"
k = 5; // COMPILER ERROR: k is const!
Always declare variables as const
if you don't need to
change their values after the initial assignment!
- avoids bugs: does not compile if you accidentally change the value later
- helps understanding your code better: clearly communicates that the value will stay the same further down in the code
- can improve performance (more compiler optimizations possible)
using real = double;
using ullim = std::numeric_limits<unsigned long>;
using index_vector = std::vector<std::uint_least64_t>;
Prefer the more powerful (we'll later see why) using
over
the outdated and ambiguous typedef
!
auto variable = expression;
- variable type deduced from right hand side of assignment
- often more convenient, safer and future proof
- also important for generic (type independent) programming
auto i = 2;
auto u = 56u;
auto d = 2.023;
auto f = 4.01f;
auto l = -78787879797878l;
auto x = 0 * i;
auto y = i + d;
auto z = f * d;
// two simple functions:
constexpr int cxf (int i) { return i*2; }
int foo (int i) { return i*2; }
// OK '2' is a literal:constexpr int i = 2; // OK '2' is a literal
// OK, 'cxf' is constexpr:constexpr int j = cxf(5); // OK, cxf is constexpr
// OK, 'cxf' and i are constexpr:constexpr int k = cxf(i); // OK, cxf and i are constexpr
int x = 0; // not constexpr
// non-constexpr context: int l = cxf(x); // OK// OK, not a constexpr context
// constexpr contexts:
// constexpr int m = cxf( x ); //
// constexpr int n = foo( 5 ); //