ProgrammingC++ Embedded Developer

Describe how link-time and compile-time constancy works in C++. What is the difference between constexpr and const? When should each be used?

Pass interviews with Hintsage AI assistant

Answer.

In C++, there is compile-time (constancy at compile time) and link-time (at link time) constancy.

  • A const variable is an object that cannot be changed after initialization. However, const does not always guarantee that the value is known at compile time; it may only be computed at runtime.
  • constexpr ensures that an expression or function will be evaluated at compile time.

Example:

const int x = time(0); // const but NOT constexpr: value is computed at runtime constexpr int y = 2 + 2; // constexpr: known at compile time constexpr int square(int x) { return x * x; } int arr[square(3)]; // array size is a compile-time expression

Use constexpr for constant expressions that need to be available to the compiler, such as for array sizes or template parameters.

Trick question.

Can a function declared as constexpr be called with non-constant arguments?

Answer: Yes! If the arguments are known at compile time, the result will be computed at compile time. If the arguments are only known at runtime, the function will be evaluated like a regular one.

constexpr int double_val(int x) { return x * 2; } int val = std::rand(); int result = double_val(val); // Will be called at run-time

Examples of real errors due to ignorance of the nuances of the topic.


Story

One of the modules specified the size of an array using const int, expecting it to be a compile-time constant. On another compiler, this caused an error because the value was computed at run-time, and the array size did not conform to the standard.


Story

In hash calculations, the compiler could not optimize calculations because a const variable was used instead of constexpr. The result: a performance drop of more than 2 times in new releases.


Story

When migrating to modern standards, the keywords were confused, and a function was declared as const instead of constexpr, causing the result to be unusable in compile-time expressions of templates. Quick diagnostics revealed the error, but it went into master during code review.