-1

see code below, f() is defined below main function is regarded as ill-formed ? could anyone give me an explanation for this ?

constexpr  int f ();
void indirection ();
int main () {
  constexpr int n = f (); // ill-formed, `int f ()` is not yet defined
  indirection ();
}
constexpr int f () {
  return 0;
}
void indirection () {
  constexpr int n = f (); // ok
}
0

2 Answers 2

2

The C++14 standard provides the following code snippet (shortened by me for convenience):

constexpr void square(int &x); // OK: declaration

struct pixel { 
    int x;
    int y;
    constexpr pixel(int); 
};

constexpr pixel::pixel(int a)
    : x(a), y(x) 
{ square(x); }

constexpr pixel small(2); // error: square not defined, so small(2)
                        // is not constant so constexpr not satisfied

constexpr void square(int &x) { // OK: definition
   x *= x;
}

The solution is to move the definition of square above the the declaration of small.

From the above we can get to the conclusion that it's fine to forward declare constexpr functions, but their definitions have to be available prior to their first use.

Sign up to request clarification or add additional context in comments.

Comments

2

A constexpr something has to be known at compile time, at each point where it's used.

This is essentially the same as you cannot declare a variable of an incomplete type, even if that type is fully defined later in the same source.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.