The following code compiles fine and runs successfully.
#include <iostream>
constexpr int f();
int main()
{
int a = f();
std::cout << a << "\n";
// error: ‘constexpr int f()’ used before its definition
// constexpr int b = f();
// std::cout << b << "\n";
}
constexpr int f()
{
return 10;
}
Here is the output.
$ g++ -std=c++11 foo.cpp && ./a.out
10
But when I uncomment the two lines of code in comments, I get this error.
$ g++ -std=c++11 foo.cpp && ./a.out
foo.cpp: In function ‘int main()’:
foo.cpp:11:25: error: ‘constexpr int f()’ used before its definition
constexpr int b = f();
^
I know that I can get rid of this error quite easily by moving the definition of constexpr int f()
before main()
.
Here are my questions:
- Why must a
constexpr
function be defined before using it in aconstexpr
expression? - Why is declaring a
constexpr
function before using it in aconstexpr
not sufficient? - Why can't the compiler figure out where the
constexpr
function is defined just like it can when aconstexpr
function or a non-constexpr
function is used in a non-constexpr
expression? - Why is it okay to define a
constexpr
function after using it in a non-constexpr
expression?