final version

Expressions & Operators

Expressions: repräsentieren Berechnungen, haben Typ und Wert, entweder primär oder zusammengesetzt (mit Operatoren). Literale: konstanter Wert, fester Typ. 42u, 3.14f, “bruh”

L-WertR-Wert
Identifiziert Speicherplatz
(Adresse!)
Jeder L-Wert kann als R-
Wert benutzt werden
Kann Wert ändern (z.B.
Zuweisung)
Kann Wert nicht ändern
e.g. Variablee.g. Literal
y - R-Werte: R*R, !R, L++
  • L-Werte: L=R, L+=R, ++L, L>>R, L<<R

(-> means from left, <- from right)

Prec.OperatorDescriptionAss.
1::scope resolution->
2a++ a--, a(), a[], .->suffix incr./decr.
function call
subscript
member access
<-
3++a --a, +a -a, !, *a, &a, new new[], delete delete[]prefix incr./decr.
unary plus/minus
logical NOT
dereference
address of
alloc
dealloc
->
5a*b a/b a%bmult, div, rem->
6a+b a-badd, subtr->
8<=>three-way-comp (?)->
9< <= > >=order relations->
10== !=equality relations->
14&&logical AND->
15||logical OR->
16a ? b : c, =, += -= &= /= %=ternary op, direct assignment, plus/minus compound assignment, mult/div/rem comp ass<-
17,comma->
  • % only works for int, uint

Modulo: Es gelten und .

std library

std::swap(a,b) // swaps values
std::sqrt(a) // square root
std::abs(a,b) // absolute difference between a,b

Types

  • conversion: char/bool < int < uint < float < double
  • prefixes: 0b binär; 0x hexadec; 0 oktal(!) int
  • signed = ; max = 2’147’483’647
  • unsigned = ; max = 4’294’967’295

char/string

  • ' char, " string
  • size = 1 Bytes = 8 Bits

float/double

-> basis, precision, min/max power

normalisiertes Fliesskommasystem:

-> , sowie Zahlen kleiner als haben keine normalisierte Darstellung

Anzahl Zahlen im positiven normalisierten System:

-> mit negativen Zahlen verdoppelt sich die Anzahl möglicher Zahlen

Number Representation

Rule

  1. Don’t compare rounded floats
  2. Dont add two floats of different magnitudes
  3. Dont subtract two floats of similar magnitudes
  • verlustbehaftete Operationen möglichst spät ausführen
  • when adding floats, always start with the smallest number (reducing rounding error)

base conversion

hexbindechexbindec
000000810008
100011910019
200102a101010
300113b101111
401004c110012
501015d110113
601106e111014
701117f111115
HexDecHexDecHexDecHexDec
000406480128c0192
1016508090144d0208
20326096a0160e0224
304870112b0176f0240

Primzahltest (n = Input):

unsigned int d;
for(d = 2; n%d != 0; ++d);
bool is_prime = (n == d);
 

Dec2bin (x ganze Zahl)

for (p = 1; p <= x / 2; p *= 2); // 2p <= x
	for (; p != 0; p /= 2) {
		if (x >= p) {
			std::cout << "1";
			x -= p; }
		else std::cout << "0"; }
  • works with any base

Dec2bin (0 < x < 2; float/double)

for (int b_0; x != 0; x = 2 * (x - b_0)) {
	b_0 = (x >= 1);
	std::cout << b_0; } // d0.d1-dn

variables

Don't change variable values inside an R-expression!

  • Scopes {...} -> variables declared inside not accessible outside
  • Shadowing -> usage of same variable name as outside of scope
int i = 2;
for (int i = 0; i < 4; ++i) cout << i; // 0123
cout << i; // 2

functions

non-void function without return leads to undefined behaviour

overloading

  • compiler chooses best-fitting function
void print(double d);
void print(const std::string& str);

const

void process(const int data); // Can't modify `data`
  • const member functions
class MyClass {
    int value;
    public:
    int getValue() const { return value; } // Doesn't modify `value`
    void setValue(int v) { value = v; }    // Modifies `value`
};
 
  • dangling reference:
int& dangerous() {
    int x = 42; // Local variable
    return x;}  // Dangling reference

pointers

  • &a get address
  • *a get value
  • p->n == (*p).n

const

  • const T var T const var (same for T&)
read from right to left
int const p1const int
int const* p2const int, pointer
int* const p3int, const pointer
int const* const p4const int, const pointer
dangling pointer
  • A pointer that points to a memory location that has been freed.
int* ptr = new int(10);
delete ptr;
// ptr is now dangling

multiple delete

int* ptr = new int(10);
delete ptr;
delete ptr; // Undefined behavior

Deleting same memory multiple times leads to undefined behaviour

Smart Pointers

std::unique_ptr (not further discussed)

#include <memory>
std::unique_ptr<int> ptr(new int(10));
// transfer ownership
std::unique_ptr<int> ptr2 = std::move(ptr);

std::shared_ptr

  • can be used exactly like normal (raw) pointers:
std::shared_ptr<int> ptr(new int(10));
// copying
std::shared_ptr<int> ptr2 = ptr;

dynamic data types

new/delete

  • new -> delete after usage
  • delete without new causes Laufzeitfehler
  • for arrays: new[] -> delete[]

arrays

std::vector

#include <vector>
std::vector<T> name(length, init_val)
std::vector<T> name = {1,2,3};
// wahlfreier zugriff
T t = v[i];
T t = v.at(i) // returns error if outside bounds
// iteration (requires multiplication + addition per iteration)
for (int i=0; i<3;i++) cout << v[i];
// sqeuential interator
for (<T>::iterator it = v.begin(); it != v.end(); ++it)
std::cout << *it; // prints 000
  • iteration ineffizient, requires multiplication + addition / iteration
  • member functions: size, push_back, begin, end, pop_back, insert, swap

Accessing elements outside bounds of vector leads to undefined behavior.

std::string

  • initalisation
#include <string>
using namespace std;
 
string str1 = "Hello";
string str2("World");
string str3(5, 'a'); // "aaaaa"
  • operations
// concatenation
string str4 = str1 + " " + str2; // "Hello World"
str1 += " C++"; // "Hello C++"
// acessing chars
char ch = str1[0]; // 'H'
// length (returns uint/t_size)
int len = str1.length(); // or str1.size()
  • methods
// substring
string substr = str1.substr(0, 5); // "Hello"
// find
size_t pos = str1.find("C++"); // Position of "C++"
// replace
str1.replace(6, 3, "Cpp"); // "Hello Cpp"
// erase
str1.erase(6, 3); // "Hello "
// insert
str1.insert(6, "Cpp"); // "Hello Cpp"
// to int/double/string
int num = stoi(str1);
double dbl = stod(str1);
string str = to_string(123);
  • comparison, iteration
if (str1 == str2) { /* ... */ }
if (str1 < str2) { /* ... */ }
// range-based
for (char& ch : str1) {}
// index-based
for (std::string::size_type i = 0; i < str.length(); ++i) {}
// iterator
for (std::string::iterator it = str.begin(); it != str.end(); ++it) {}

classes

  • functions:
struct Cl {
	int val;
	// constructor
	Cl(int value = 0) : val(value) {};
	// deconstructor
	~Cl();
	// copy constructor
	Cl(const Cl& other);
	// assignment operator
	Cl& operator=(const Cl& other);
 
	// operator overloading
	Cl operator+(const Cl& other);
	bool operator==(const Cl& other);
	// stream overloading (can be left away inside class, if it doesn't need access to private vars)
	friend std::ostream& operator<<(std::ostream& stream, const Cl& obj);
	friend std::istream& operator>>(std::istream& stream, Cl& obj);
};
 
// example << overload
std::ostream& operator<<(std::ostream& stream, const Cl& obj) {
	stream << obj.val;
	return stream;
};
std::istream& operator>>(std::istream& stream, Cl& obj) {}

Rule of three

If a type (that manages dynamic memory) defines one of these structures, it needs to implement all three

  • Deconstructor
  • Copy Constructor
  • Assignment operator

other

  • ascii
dechexvalue
0-310-1Fspecial chars
32-4720-2Fspace, !"#$%&'()*+,-./
48-5730-39digits (0-9)
58-643A-40:;>=<?@
65-9041-5Acapital letters (A-Z)
91-965B-60`[]^_“
97-12261-7Aletters (a-z)
123-1277B-7F{|}~, DEL