I'm having some trouble with constexpr
. The book C++ Primer shows a line of code:
constexpr int sz = size(); // only size() is a constexpr function
// this code is right
However the book doesn't give a specific example. So I try the following code by myself:
#include <iostream>
constexpr int fun();
int main()
{
constexpr int f = fun();
std::cout << f << std::endl;
}
constexpr int fun()
{
return 3;
}
But my compiler said fun()
is undefined.
If I change constexpr
into const
, it works well, and if I change my code to define the constexpr function before use:
#include <iostream>
constexpr int fun()
{
return 3;
}
int main()
{
constexpr int f = fun();
std::cout << f << std::endl;
}
It also works well. Can someone tell me why?
See Question&Answers more detail:os