all: $(MAKE) -C lecture \ No newline at end of file _config.yml 0 → 100644  # Configuration of Jekyll url: "http://localhost:4000/" baseurl: "file:///home/spraetor/lehre/scprog-so2021/_presentation" source: presentation/ destination: _presentation/ exclude: [] keep_files: [contrib, css, fonts, images, js] # Site settings title: "Scientific Programming with C++" institute: "Institute of Scientific Computing" email: simon.praetorius@tu-dresden.de description: "Lecture slides for SCPROG Scientific Programming, Advanced Aspects So2021" author: "Dr. Simon Praetorius" semester: "Summer term 2021" collections: - slides \ No newline at end of file  ... ... @@ -56,20 +56,20 @@ We want to solve the task$\mathbf{y} = \alpha A\mathbf{x} + \beta \mathbf{y}$( and$\alpha=\beta=1$for simplicity. % \begin{minted}{c++} DenseVector y(m, 0.0); DenseVector y(n, 0.0); \end{minted} First, we are using the library CBLAS: % \begin{minted}{c++} int m = A.rows(); // number of rows of the matrix A int n = A.cols(); // number of columns of the matrix A int lda = std::max(1,m); // Specifies the leading dimension of array storing the value of A int n = A.rows(); // number of rows of the matrix A // == number of columns of the matrix A int lda = std::max(1,n); // Specifies the leading dimension of array storing the value of A int incx = 1; // Specifies the increment for the elements of x int incy = 1; // Specifies the increment for the elements of y double alpha = 1.0, beta = 1.0; cblas_dgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, &A, lda, cblas_dgemv(CblasRowMajor, CblasNoTrans, n, n, alpha, &A, lda, &x, incx, beta, &y, incy); \end{minted} % ... ... @@ -111,54 +111,54 @@ performance and how to test and optimize your implementation. Classical design p the twin lecture SCPROG -- Fortgeschrittene Konzepte des Wissenschaftlichen Programmierens: OOP mit Java -- by Prof. W. Walter. \section{Structure of the lecture and tutorial} This module focuses on three learning goals: \begin{enumerate}[1)] \item Programming with C++ \item Working with programming tools \item Discovering scientific C++ software libraries \end{enumerate} % \section{Structure of the lecture and tutorial} % This module focuses on three learning goals: % \begin{enumerate}[1)] % \item Programming with C++ % \item Working with programming tools % \item Discovering scientific C++ software libraries % \end{enumerate} There will be a tutorial every week with exercises. The corresponding exercise sheets can be found online in a Git repository at % There will be a tutorial every week with exercises. The corresponding exercise sheets can be found online in a Git repository at \url{https://gitlab.mn.tu-dresden.de/teaching/scprog/wi2019} % \url{https://gitlab.mn.tu-dresden.de/teaching/scprog/so2021-tutorial} On each exercise sheet there are a few exercises marked for submission. Approximately two weeks you have time to work on the tasks and are supposed to submit your solutions into the Git repository itself. Therefore, in the first tutorials you get an account and have to create a Git project on the TU-Dresden local GitLab server \url{https://gitlab.mn.tu-dresden.de}. The details about this are explained on the repository README page and are presented in the first tutorial. The advantage you have from submitting the exercises is 1. you get a personal review and feedback, 2. you learn how to work in a cooperative environment on scientific projects, and 3. you can get a bonus for the final oral exam (reaching 66\% of the possible exercise points gives a bonus of up to a grade of 0.3). % On each exercise sheet there are a few exercises marked for submission. Approximately two weeks you have time to work on the tasks % and are supposed to submit your solutions into the Git repository itself. Therefore, in the first tutorials you get an account and % have to create a Git project on the TU-Dresden local GitLab server \url{https://gitlab.mn.tu-dresden.de}. The details about this are % explained on the repository README page and are presented in the first tutorial. The advantage you have from submitting the exercises % is 1. you get a personal review and feedback, 2. you learn how to work in a cooperative environment on scientific projects, and 3. you % can get a bonus for the final oral exam (reaching 66\% of the possible exercise points gives a bonus of up to a grade of 0.3). \subsection{Course outline} \begin{itemize} \item Best practice in scientific programming \item C++ basics (data-types, operators, pointers, arrays, references,$\ldots$) \item Scopes, Namespaces, Functions \item Overloading, Specialization \item Basics of object-oriented class design, inheritance, polymorphie \item Generic Programming with templates \item Generic Design patterns (Functors, Iterators, Type-Traits) \item Algorithms and Data-Structures in the C++ standard library \item Meta-Programming \item Expression-Templates \item (Compile-Time symbolic differentiation) \end{itemize} % \subsection{Course outline} % \begin{itemize} % \item Best practice in scientific programming % \item C++ basics (data-types, operators, pointers, arrays, references,$\ldots$) % \item Scopes, Namespaces, Functions % \item Overloading, Specialization % \item Basics of object-oriented class design, inheritance, polymorphie % \item Generic Programming with templates % \item Generic Design patterns (Functors, Iterators, Type-Traits) % \item Algorithms and Data-Structures in the C++ standard library % \item Meta-Programming % \item Expression-Templates % \item (Compile-Time symbolic differentiation) % \end{itemize} \section{Literature and material} There is a lot of good (and a lot of bad) literature on C++ programming. Some references with links to the Slub and to online sources are given on the website % \section{Literature and material} % There is a lot of good (and a lot of bad) literature on C++ programming. Some references with links to the Slub and to online sources % are given on the website \url{https://math.tu-dresden.de/~spraetor} % \url{https://math.tu-dresden.de/~spraetor} on the subpage \texttt{Teaching/Scientific Programming with C++}, or on the README page of the repository as above. The main source for reference of C++ is the nearly complete online standard at % on the subpage \texttt{Teaching/Scientific Programming with C++}, or on the README page of the repository as above. The main source for reference of C++ is the nearly complete online standard at \url{https://en.cppreference.com} % \url{https://en.cppreference.com} and the official standard % and the official standard \url{https://github.com/cplusplus/draft}, or \\ \url{http://www.open-std.org/jtc1/sc22/wg21/} % \url{https://github.com/cplusplus/draft}, or \\ % \url{http://www.open-std.org/jtc1/sc22/wg21/} \section{History of C++} ... ... @@ -201,27 +201,27 @@ the collection \emph{Boost} was founded by some standard committee members, to p A first correction of the \cxx{98} standard was published in \textbf{2003}. It resolved several smaller or larger errors and problems in the 1998 standard and was named again after the publication year, \cxx{03} standard. In \textbf{2005} extensions of the 2003 standard were collected and summarized in the technical report TR1. Those developments were the bases for a new standard that was intended to be published in the early 2000s. This can be seen on the working title of this standard \cxx{0x}. But it needed more time and couln't be finished within the same early 2000s. This can be seen on the working title of this standard \cxx{0x}. But it needed more time and couldn't be finished within the same decade. Finally in 2011 the standard \cxx{11} was finalized and published. It contains a long list of new features (including lambda functions, constexpr, auto type deduction, decltype specifier, several library extensions like tuples, arrays, type-traits and a lot more) and was the \texttt{constexpr}, auto type deduction, \texttt{decltype} specifier, several library extensions like tuples, arrays, type-traits and a lot more) and was the biggest new release since the initial version from 1998. Since version 4.8.1. of GCC the \cxx{11} version is completely implemented. In Clang since version 3.3., in Intel ICC Compiler since version 15.0, and in Microsoft Visual Studio Compiler since version 19.0. See \url{https://en.cppreference.com/w/cpp/compiler_support} for an overview of the compiler support of C++ features. Although the \cxx{11} standard brought so many new features, some could not be complete in the standard, others needed minor fixes. This is the reason Although the \cxx{11} standard brought so many new features, some could not be completed in the standard, others needed minor fixes. This is the reason why in \textbf{2014} the next \emph{minor} revision of the standard, called \cxx{14}, was published. But it is more than a revision, it is a completion of the \cxx{11} standard. The working title of the standard was \cxx{1y} and the Compiler vendors finished their implementation of the standard with version 5 of GCC, version 3.4 of clang, version 17.0 if Intel ICC, and version 19.10 of MSVC. Due to some bugs in the implementation, the recommendation for GCC is version 6.1 for \cxx{14}, though. \cxx{14} is not the recent standard. Since the release of the \cxx{11} standard in 2011, it was decided to have a fixed release cycle of 3 years, \cxx{14} is not the most recent standard. Since the release of the \cxx{11} standard in 2011, it was decided to have a fixed release cycle of 3 years, where each new feature that is not completely ready until a some feature freeze date has to wait for the next release and not the release for the feature. The current published C++ release is \cxx{17} (working title \cxx{1z}) and the development for \cxx{20} (working title \cxx{2a}) is in its The current published C++ release is \cxx{17} and the development for \cxx{20} (working title \cxx{2a}) is in its final standardizing phase. Both standards are only partially implemented by the compiler vendors, but at least the core language features of \cxx{17} are now finished. It needs approximately 3 years after a standard is published until all feature and library components are implemented by the compilers GCC, clang, ICC, and MSVC. Proposals for new features and some discussion of the future development of C++ can be found at the ISO-standard workinggroup 21 page Proposals for new features and some discussion of the future development of C++ can be found at the ISO standard working group 21 page \url{http://www.open-std.org/jtc1/sc22/wg21/}. This diff is collapsed.  \section{Operators\label{sec:operator}} We have see already in the initial example the usage of arithmetic and many other \emph{operators}. Operators are special functions with typically prefix-notation (for unary operators) and infix notation (for binary operators) and are written with the classical mathematical symbols. In the initial example, we had \texttt{+, -, *, ::, ., <<, = , ",", ()}. We have see already in the initial example the usage of arithmetic and many other \emph{operators}. Operators are special functions with typically prefix-notation (for unary operators) and infix notation (for binary operators) and are written with the classical mathematical symbols. In the initial example, we had \texttt{+, -, *, ::, ., <<, = , ",", ()}. \begin{defn} We call operators acting on one operand \emph{unary operators} (like \texttt{-, *, \&}), acting on two operands \emph{binary operator} (like \texttt{+, -, *, /, =, +=, ...}) and even acting on three operands a \emph{ternary operators} (there is only \texttt{?:}). We call operators acting on one operand \emph{unary operators} (like \texttt{-, *, \&}), acting on two operands \emph{binary operator} (like \texttt{+, -, *, /, =, +=, ...}) and even acting on three operands a \emph{ternary operators} (there is only \texttt{?:}). \end{defn} Operators are characterized by its properties: \emph{associativity}, \emph{precedence}, and whether they can be \emph{overloaded}. ... ... @@ -19,8 +16,8 @@ Operators are characterized by its properties: \emph{associativity}, \emph{prece Only in \emph{associative compositions} the result depends on the associativity. In order to fix the meaning of expressions with multiple similar operators without brackets we introduce the convention \begin{itemize} \item A \emph{left-associative operator} is evaluated from left to right. \item A \emph{right-associative operator} is evaluated from right to left. \item A \emph{left-associative operator} is evaluated from left to right. \item A \emph{right-associative operator} is evaluated from right to left. \end{itemize} All (binary) operators are classified as left or right associative ... ... @@ -32,54 +29,54 @@ All (binary) operators are classified as left or right associative \end{example} \begin{example} Assignment operators are \emph{right-associative}: (\texttt{=, +=, <<=, ...}), \ie the expression Assignment operators are \emph{right-associative}: (\texttt{=, +=, <<=, ...}), \ie the expression \cpp{x= y= z} is evaluated from right to left and thus equivalent to: \cpp{x= (y= z)} \end{example} % ------------------------------------------------------------------------------------------------- \subsection{Precedence\label{sec:operator-precedence}} Operators are ordered by its precedence. This defines a \emph{partial ordering} of the operators and specified which operators is evaluated first. The precedence can be overridden using brackets. Operators are ordered by its precedence. This defines a \emph{partial ordering} of the operators and specified which operators is evaluated first. The precedence can be overridden using brackets. From basic arithmetics you know the precedence of some arithmetic operators, especially \texttt{+, -, *, /}. This precedence is known in some countries as mnemonics: \begin{itemize} \item Germany: \textit{Punktrechnung geht vor Strichrechnung}, meaning Multiplication/Division before Addition/Subtraction \item United States: \textbf{PEMDAS}: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. PEMDAS is often expanded to the mnemonic \textit{Please Excuse My Dear Aunt Sally}''. \item Canada and New Zealand: \textbf{BEDMAS}: Brackets, Exponents, Division/Multiplication, Addition/Subtraction. \item UK, Pakistan, India, Bangladesh and Australia and some other English-speaking countries: \textbf{BODMAS}: Brackets, Order, Division/Multiplication, Addition/Subtraction or Brackets, Of/Division/Multiplication, Addition/Subtraction. \end{itemize} \begin{example} An example with classical mathematical operators on integers: $\begin{split} x &= 2 * 2 + 2\, /\, 2 - 2\quad\Rightarrow\quad x = \left(\left(\left(2 * 2\right) + \left(2 / 2\right)\right) - 2\right) = 3 \\ y &= 8 / 2 * (2 + 2)\quad\Rightarrow\quad y = (8 / 2) * (2 + 2) = 16 \end{split}$ $\begin{split} x &= 2 * 2 + 2\, /\, 2 - 2\quad\Rightarrow\quad x = \left(\left(\left(2 * 2\right) + \left(2 / 2\right)\right) - 2\right) = 3 \\ y &= 8 / 2 * (2 + 2)\quad\Rightarrow\quad y = (8 / 2) * (2 + 2) = 16 \end{split}$ \end{example} \begin{rem} The operator \cpp{^} does not mean exponentiation or power, but the logical X-Or. In Matlab/Octave this operator has the expected meaning, but in C++ the operator has a different precedence than the power operator would have from a mathematical perspective. This means: \cppline{a = b^2 + c} is equivalent to \cppline{a = b^(2 + c)} BUT NOT TO \cppline{a = (b^2) + c} There is no power operator in C++! You have to call the function \cpp{std::pow} instead. The operator \cpp{^} does not mean exponentiation or power, but the logical X-Or. In Matlab/Octave this operator has the expected meaning, but in C++ the operator has a different precedence than the power operator would have from a mathematical perspective. This means: \cppline{a = b^2 + c} is equivalent to \cppline{a = b^(2 + c)} BUT NOT TO \cppline{a = (b^2) + c} There is no power operator in C++! You have to call the function \cpp{std::pow} instead. \end{rem} \begin{guideline}{Principle} When in doubt or to clarify the expression: use parentheses in. When in doubt or to clarify the expression: use parentheses. \end{guideline} % ------------------------------------------------------------------------------------------------- \subsection{Examples of operators} In the table below, the operators are ordered by precedence and information about associativity is given. Here I give you a summary of most of the operators and its meaning. Most of the operators are defined for arithmetic types (integers or floating-point numbers), but some are also defined for library types, like \cpp{std::string}, \cpp{std::vector} and others. In the table below, the operators are ordered by precedence and information about associativity is given. Here I give you a summary of most of the operators and its meaning. Most of the operators are defined for arithmetic types (integers or floating-point numbers), but some are also defined for library types, like \cpp{std::string}, \cpp{std::vector} and others. \subsubsection*{Arithmetic operators} \begin{tabular}{l|l} ... ... @@ -128,14 +125,13 @@ Operator & Action \\ \end{rem} \begin{rem} With \cxx{20}\marginpar{[\cxx{20}]} a new comparison operator will be introduced, called \emph{three-way comparison operator} or sometimes also \emph{space-ship operator}. It is written as \cpp{<=>} and returns an object such that \begin{itemize} \item \cpp{(a <=> b) < 0} if \cpp{lhs < rhs} \item \cpp{(a <=> b) > 0} if \cpp{lhs > rhs} \item \cpp{(a <=> b) == 0} if \cpp{lhs} and \cpp{rhs} are equal/equivalent. \end{itemize} and the returned object indicates the type of ordering (strong ordering, partial ordering, weak equality, ...). With \cxx{20}\marginpar{[\cxx{20}]} a new comparison operator is introduced, called \emph{three-way comparison operator} or sometimes also \emph{space-ship operator}. It is written as \cpp{<=>} and returns an object such that \begin{itemize} \item \cpp{(a <=> b) < 0} if \cpp{lhs < rhs} \item \cpp{(a <=> b) > 0} if \cpp{lhs > rhs} \item \cpp{(a <=> b) == 0} if \cpp{lhs} and \cpp{rhs} are equal/equivalent. \end{itemize} and the returned object indicates the type of ordering (strong ordering, partial ordering, weak equality, ...). \end{rem} \subsubsection*{Bitwise operators} ... ... @@ -153,15 +149,11 @@ Operator & Action \\ \end{tabular} \begin{rem} The logical operators \cpp{<<} and \cpp{>>} are used in C++ often in a different context, namely to \emph{shift} something into a \emph{stream}. Streams are abstractions devices allowing input and output operations. The operator \cpp{<<} is therefore called \emph{insertion operator} and is used with output streams, whereas the operator \cpp{>>} is called \emph{extraction operator} and is used with input streams. The logical operators \cpp{<<} and \cpp{>>} are used in C++ often in a different context, namely to \emph{shift} something into a \emph{stream}. Streams are abstractions devices allowing input and output operations. The operator \cpp{<<} is therefore called \emph{insertion operator} and is used with output streams, whereas the operator \cpp{>>} is called \emph{extraction operator} and is used with input streams. \end{rem} \begin{example} While a modern CPU efficiently implements arithmetic and logical operators on integers, one could implement those manually, by using bitwise operations and comparison with 0 only. The following pseudo code implements multiplication of two integers \texttt{a} and \texttt{b} with bit shifts, comparison and addition: While a modern CPU efficiently implements arithmetic and logical operators on integers, one could implement those manually, by using bitwise operations and comparison with 0 only. The following pseudo code implements multiplication of two integers \texttt{a} and \texttt{b} with bit shifts, comparison and addition: \begin{minted}{pascal} c := 0 solange b <> 0 ... ... @@ -171,23 +163,22 @@ Operator & Action \\ schiebe b um 1 nach rechts return c \end{minted} It implements kind of a manual multiplication in the binary base but in the uncommen order from right to left. It implements kind of a manual multiplication in the binary base but in the uncommon order from right to left. \footnote{See \url{https://de.wikipedia.org/wiki/Bitweiser_Operator}} As an exercise, you could implement this algorithm and compare the result with the classical multiplication. \end{example} \subsubsection*{Assignement operators} Compound-assignment operators like \cpp{+=, -=, *=, /=, %= >>=, <<=, &=, ^=, |=} apply an operator to the left and right-side of an assignment, and store the result in the left operand. \subsubsection*{Assignment operators} Compound-assignment operators like \cpp{+=, -=, *=, /=, %= >>=, <<=, &=, ^=, |=} apply an operator to the left and right-side of an assignment, and store the result in the left operand. Example: \cppline{a += b // corresponds to a = a + b} \begin{rem} Compared to the simple assignment, a compound-assignment does not need to create a temporary and maybe copy it to the left-hand side operand, but works with the operand directly. Compared to the simple assignment, a compound-assignment does not need to create a temporary and maybe copy it to the left-hand side operand, but works with the operand directly. \begin{minted}{c++} \begin{minted}{c++} struct A { double value; }; A operator+(A const& a, A const& b) { ... ... @@ -195,20 +186,18 @@ Compared to the simple assignment, a compound-assignment does not need to create c += b; return c; } \end{minted} but \begin{minted}{c++} \end{minted} but \begin{minted}{c++} A& operator+=(A& a, A const& b) { a.value += b.value; return a; } \end{minted} \end{minted} \end{rem} \subsubsection*{Bracket-Access operators} The round brackets \cpp{()} and the square brackets \cpp{[]} also represent operators, namely \emph{bracket-access operators}. While the square bracket is typically used as vector access and allows only one argument, \eg the vector element index, the round brackets represent a function call and thus allow any number of arguments \texttt{>= 0}. The round brackets \cpp{()} and the square brackets \cpp{[]} also represent operators, namely \emph{bracket-access operators}. While the square bracket is typically used as vector access and allows only one argument, \eg the vector element index, the round brackets represent a function call and thus allow any number of arguments \texttt{>= 0}. \subsection*{Sequence of evaluation and side effects} A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. ... ... @@ -219,20 +208,18 @@ Logical and-then/or-else (\cpp{&&} and \cpp{||}) operators, ternary \cpp{?:} que With \cxx{17}\marginpar{[\cxx{17}]} several more operations are now sequenced and are safe to include side effects. But in general, you should know that \begin{guideline}{Attention} When you use an expression with side effects multiple times in the absence of sequence points, the resulting behavior is \textbf{undefined} in C++. Any result is possible, including one that does not make logical sense. When you use an expression with side effects multiple times in the absence of sequence points, the resulting behavior is \textbf{undefined} in C++. Any result is possible, including one that does not make logical sense. \end{guideline} See also: \href{http://en.wikipedia.org/wiki/Sequence_point}{Wikipedia}, \href{http://en.cppreference.com/w/cpp/language/eval_order}{CppReference.com} For logical operators, at first the left operand is evaluated and based on its value it is decided whether to evaluate the right operand at all or not, \ie For logical operators, at first the left operand is evaluated and based on its value it is decided whether to evaluate the right operand at all or not, \ie \begin{minted}{c++} A && B // first evaluate A, if A == true evaluate B and return its value A || B // first evaluate A, if A == false, evaluate B andreturn its value A || B // first evaluate A, if A == false, evaluate B and return its value A ? B : C // first evaluate A, if true, evaluate B, otherwise evaluate C (A,B,C, ...) // first evaluate A, then evaluate B, then evaluate C, ... f() + g() // it is not specified whether f is evaluate first or g f() + g() // it is not specified whether f is evaluated first or g \end{minted} \begin{guideline}{Principle} ... ... @@ -241,7 +228,7 @@ at all or not, \ie \begin{rem} The precedence property is not related to the order of evaluation, but to the rank of the operator. For an arbitrary function \cpp{f(a,b,c,d)} it is not specified in which order the expressions for a, b, c, d are evaluate. is not specified in which order the expressions for a, b, c, d are evaluated. \end{rem} \begin{example} ... ... @@ -250,7 +237,7 @@ at all or not, \ie int foo(int a, int b) { return a + b; } int x = 1; foo(++x, x++); // Variant 1 (undefined behavior) foo(++x, x++); // Variant 1 (unspecified behavior) x = 1; int a = ++x, b = x++; ... ... @@ -260,16 +247,13 @@ at all or not, \ie \subsection{Operators as functions} In C++ nearly all operator can be written (and called) as a regular function. Let \texttt{o} be the symbol of the operator, \eg \texttt{o$~\in$\{+,*,(),+=,<,...\}}, then there zero, one or both of the following implementations are available: In C++ nearly all operator can be written (and called) as a regular function. Let \texttt{o} be the symbol of the operator, \eg \texttt{o$~\in$\{+,*,(),+=,<,...\}}, then there zero, one or both of the following implementations are available: \begin{minted}[frame=none]{c++} Result operator o(Arg1 a, Arg2 b, ...) // a o b Result Arg1::operator o(Arg2 b, ...) // Arg1 a; a o b \end{minted} The variant 1 implement the operator as a free function, whereas the variant 2 implements the operator as a member function of a class, where \texttt{Arg1} is the name of that class. Whether there is a function representation of the operator and whether it is allowed to \emph{overload} that function is specified in the table below. The variant 1 implement the operator as a free function, whereas the variant 2 implements the operator as a member function of a class, where \texttt{Arg1} is the name of that class. Whether there is a function representation of the operator and whether it is allowed to \emph{overload} that function is specified in the table below. \subsection*{Overview} \begin{tabular}{c|l|l|l|l} ... ... @@ -322,7 +306,6 @@ that function is specified in the table below. [note 1]: \#$~\in\{$\cpp{+, -, *, /, %, <<, >>, &, ^, |}$\}$In the column \textit{Overload} means (C), the operator can only be implemented as member function of a class, whereas$\checkmark$allows to write the operator as member function or free function. In the column \textit{Overload} means (C), the operator can only be implemented as member function of a class, whereas$\checkmark\$ allows to write the operator as member function or free function. A more complete table can also be found at \url{http://en.wikipedia.org/w/index.php?title=C++\_operators}, or \url{https://en.cppreference.com/w/cpp/language/operator_precedence}.
 --- class: center, middle # Introduction --- # Scientific Programming with C++ ## What is Scientific Programming? - Efficient code for scientific application in Mathematics, Biology, Physics,... - (High-performance) computing on CPUs, GPUs and other processors - Requires knowledge about computer arithmetics, numerics and software development - Analysis of performance, test for accuracy, provide type-safety -- ## Why C++? - *Matlab* / *Python* high-level languages for fast prototyping - Highly efficient numerical libraries written in C++ - Low-level programming language for fine control about data and processing - Multi-paradigm development: OOP, Generic, Functional, Meta-programming,... - Standardized, industry ready programming language --- # Introductory example .pure-g[.pure-u-14-24[ c++ #include #include using namespace mtl; int main(int argc, char** argv) { int const size = 40, N = size * size; using matrix_t = compressed2D; // Set up a matrix 1,600 x 1,600 with // 5-point-stencil matrix_t A{N, N}; mat::laplacian_setup(A, size, size); // Compute b = A*x with x == 1 dense_vector x{N, 1.0}, b; b = A * x; std::cout << two_norm(b) << std::endl; }  ].pure-u-10-24[.gutter-64[ Even this small example contains: - modules and namespaces, - functions and blocks, - variables and types, - classes and templates ]]] --- # Compiling C++ Code - C++ is a compiler based language, i.e., one has to translate the source code of the program into a machine executable format using another program, called the **compiler**. Examples: *g++*, *clang*, *MSVC*. - Source code files, or just *source files*, typically have a filename suffix like .cc, .cxx, or .cpp and build **translation units**. - Output of the compiler: collection of **object files**. - Executable generated, by combining object files and libraries by **linker**. -- ## Example Source file mat_vec.cc compiled into executable mat_vec:  c++ [options...] mat_vec.cc [-o mat_vec]  and afterwards run the program via ./mat_vec. --- # Entry-point into a C++ program c++ int main(); int main(int argc, char* argv[]); // or int main(argc, char** argv)  - Each C++ program must contain exactly one main(...) function, while both variants are allowed. - Argument argc will be filled with number of command-line parameters and argv with character arrays (strings) of the command-line parameters. - First parameter argv contains name of the executed program. - Returns a status code: 0 means no error. - Comments start with // and span the rest of the line. - Multi-line comments: /* ... */ \ No newline at end of file
 --- class: center, middle # Variables and Datatypes --- # Variables and Datatypes C++ is a **statically typed** language. - Each identifier and expression has a property called *type*. - The type restricts the *operations* that are permitted for those entities. - It provides *semantic meaning* to the otherwise generic sequences of bits. - The type is *fixed* and *known* to the compiler. > .h3[C++-Standard (N4835) §7.1 (1):] An expression is a sequence of operators and operands that specifies a computation. > An expression can result in a value and can cause side effect. -- ## Fundamental types - The language defines datatypes that are built into the compiler - Basic types categorized as *integral types*, *floating-point types*, and *void* --- # Variables and Datatypes ## Integral types - The boolean type bool with two possible values true and false. - Character types char, signed char and unsigned char. - Basic integer type: int, can be equipped with *modifiers*: * **Signedness**: signed, unsigned * **Size**: short, long, long long - Additional basic types: std::size_t, std::int32_t,... ### Examples c++ true, false // bool 'c', '/', '\n', '0' // char 0, 123, 635u, 745l, 9993ll // int, int, unsigned, long, long long 1234567898765432 // smallest int type that can represent number  --- # Variables and Datatypes ### Representable range: - Signed int: $$-2^{N-1}\ldots 2^{N-1}-1$$ with $$N$$ the width of the type in bits. - Unsigned int: $$0\ldots 2^{N}-1$$, arithmetic operations modulo $$2^N$$ - Representation by [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement) ### Data models - Defines width of integer types (int/long/pointer) - 32 bit systems: