Seminar 7 (CPP)

7


C/CPP build.

Tasks

Task 0

Use macros to implement custom casserts:

int foo() { return 1; }
int y = 2;

int main() {
    assert(foo() > y);
}

Output must be:

$ ./a.out
a.out: a.cc:7: int main(): Assertion `foo() > y' failed.

Task 1

Update the assert macro so that it has two options:

  • assert(EXPR)  —  has the same behaviour

  • assert(EXPR, MSG)  —  add a custom message MSG

When the sources are compiled with -DNDEBUG, all asserts must be ignored, e.g. the code below must not print anything:

int foo() { std::cout << "Hi"; return 1; }
int y = 2;

int main() {
    assert(foo() > y);
}

Task 2

Try compiling the code below with -O0 .. -O3. What happens?

int i = 1;
while (i > 0) { i++; }
std::cout << "hi\n";