13

Consider the following code:

constexpr unsigned f(unsigned x)
{
    while (x & 1) x *= 3;
    return x;
}

int main()
{
    char a[f(2)];
    char b[f(1)];
}

In case it isn't obvious: for odd integers x, the function f never terminates.

When I compile the above program with clang on coliru, b seems to be a VLA, but not a:

warning: variable length arrays are a C99 feature [-Wvla-extension]

char b[f(1)];

Is there a well-defined limit at which the compiler decides to stop evaluation of a constant expression? Or would it be perfectly fine for a conforming compiler to go into an infinite loop? Does f(1) yield UB?

stefan
  • 10,215
  • 4
  • 49
  • 90
fredoverflow
  • 256,549
  • 94
  • 388
  • 662

1 Answers1

8

There are a number of things which means that an expression is not a core constant expression is

-- an invocation of a constexpr function or a constexpr constructor that would exceed the implementation defined recursion limits;

(fifth point in §5.19/2.). So the limit is implementation defined.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 4
    Turns out that C++14 has changed this to just "an expression that would exceed the implementation-defined limits", to cover also non-recursive limits, in this case "Full-expressions evaluated within a core constant expression" – Johannes Schaub - litb Mar 05 '14 at 17:16
  • See Annex B: "Full-expressions evaluated within a core constant expression [1 048 576]." – Sebastian Redl Mar 05 '14 at 17:19
  • @JohannesSchaub-litb Yes. I started looking, and then lost track of the original expression. It is a good question: there have to be some limits, or the compiler will never stop. – James Kanze Mar 05 '14 at 18:32
  • Right now the correct quotes are in the comments but they should be in the answer so we can delete the comments as obsolete. – Shafik Yaghmour Mar 06 '14 at 16:29