C++ constexpr – Value can be evaluated at compile time?

  • A+
Category:Languages

I was reading about constexpr here:

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time.

When I first read this sentence, it made perfect sense to me. However, recently I've come across some code that completely threw me off. I've reconstructed a simple example below:

#include <iostream>  void MysteryFunction(int *p);  constexpr int PlusOne(int input) {   return input + 1; }  int main() {   int i = 0;   MysteryFunction(&i);   std::cout << PlusOne(i) << std::endl;    return 0; } 

Looking at this code, there is no way for me to say what the result of PlusOne(i) should be, however it actually compiles! (Of course linking will fail, but g++ -std=c++11 -c succeeds without error.)

What would be the correct interpretation of "possible to evaluate the value of the function at compile time"?

 


A constexpr function may be called within a constant expression, provided that the other requirements for the evaluation of the constant expression are met. It may also be called within an expression that is not a constant expression, in which case it behaves the same as if it had not been declared with constexpr. As the code in your question demonstrates, the result of calling a constexpr function is not automatically a constant expression.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: