From 95ef4f720d4dc7c982369e365dbdfcf901ada3ff Mon Sep 17 00:00:00 2001 From: Alex Hirsch Date: Thu, 22 Oct 2020 12:46:23 +0200 Subject: [PATCH] Exercises: Add task0[45] --- exercises/README.md | 22 ++++++++++++++++++++++ exercises/task04/iterations.cpp | 19 +++++++++++++++++++ exercises/task05/strange.cpp | 23 +++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 exercises/task04/iterations.cpp create mode 100644 exercises/task05/strange.cpp diff --git a/exercises/README.md b/exercises/README.md index a391f3d..46e56fa 100644 --- a/exercises/README.md +++ b/exercises/README.md @@ -43,3 +43,25 @@ It depends on all three libraries. CMake itself is a build system generator. You can choose from a variety of target build systems. + +## Task 04 + +Examine the program [`iterations.cpp`](task04/iterations.cpp) and think about the expected output. +Compile the program and run it. +What do you notice? +Did you expect this behaviour? +Did you get any compiler warnings? +Investigate what is actually happening (consider using `valgrind` or a debugger). + +How can such errors be prevented? +Look for tools (e.g. static code analysers) which help discovering such faulty code. + +**Note:** If you run the executable and everything seems normal, try changing the initial content of `xs`, using different optimisation flags, or a different compiler. +The actual behaviour of this executable depends on various factors. + +## Task 05 + +You are given the program [`strange.cpp`](task05/strange.cpp). +Compile it with different compilers and optimisation flags. +What do you notice? +What is really happening here? diff --git a/exercises/task04/iterations.cpp b/exercises/task04/iterations.cpp new file mode 100644 index 0000000..b49ff9e --- /dev/null +++ b/exercises/task04/iterations.cpp @@ -0,0 +1,19 @@ +#include +#include + +int main() +{ + std::vector xs{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + + for (auto it = xs.begin(); it != xs.end(); ++it) { + for (int i = 0; i < *it; i++) { + xs.push_back(*it); + } + } + + std::cout << "Vector: "; + for (const auto &x : xs) { + std::cout << x << " "; + } + std::cout << "\n"; +} diff --git a/exercises/task05/strange.cpp b/exercises/task05/strange.cpp new file mode 100644 index 0000000..881d8f9 --- /dev/null +++ b/exercises/task05/strange.cpp @@ -0,0 +1,23 @@ +#include + +int array[5] = {}; + +bool contains(int v) +{ + for (int i = 0; i <= 5; ++i) { + if (array[i] == v) { + return true; + } + } + return false; +} + +int main() +{ + for (int i = 0; i < 10; ++i) { + auto contains_text = contains(i) ? "contains " : "does not contain "; + std::cout << "array " << contains_text << i << std::endl; + } + + std::cout << "done" << std::endl; +}