Skip to content
Exercise · Building and the Preprocessor · lesson 8 of 8

Exercise: macros to constexpr

Replace the three macros in the file:

  • kMaxUsers with a constexpr int constant equal to 100;
  • square(x) with the function constexpr int square(int x), which returns the square of x;
  • half(x) with the function constexpr int half(int x), which returns x / 2.

Keep the names: the tests use them and also check that kMaxUsers, square and half are no longer macros. The line #if defined(square) in the tests checks whether such a macro is defined.

  • square(2 + 1) → 9
  • 100 / square(5) → 4
  • half(10 + 4) → 7

Constraints: x is any int value, negative ones too, and its square fits in an int; the tests compute one call of square at compile time.

Do not add extra #include lines unless the task says so explicitly.

macros.cpp — cpp
cpp · 4 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way