Const fn that does not return

How does the compiler deal with const functions that take too long to evaluate at compile time?

Seems there is no warning - but I assume it tries to evaluate them and then gives up if they do not complete in a finite number of steps?
Where is the limit?

const fn eval() -> usize {
    let i = 1;
    while i < 5 {}
    i
}

fn main() {
    let x = eval();
    println!("Hello, world! {}", x);
}

It used to have a configurable (on nightly) limit, however as of the next release this will instead be a lint which you can toggle on and off (or set to warn for exponentially backing off warnings).

But note that your given code will compile and then loop forever at run time, because you didn't call eval in a compile-time context. Hence the change in my playground:

 fn main() {
-    let x = eval();
-    println!("Hello, world! {}", x);
+    const X: usize = eval();
+    println!("Hello, world! {}", X);
 }
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.