Skip to content

Comment on Curious C++ Lambda Examples: Recursion, constexpr, Containers C++23 includedparent

Comments

Can the compiler statically prove that it’ll not cause stack overflow? Otherwise recursion seems quite unsafe.

Naturally (if we remember our Turing machine computational capability analysis), the compiler cannot generally prove things about recursive functions, including how deep the recursion will go.

What it can do in practice is use (configurable) hard limits on the depth and on the amount of time for evaluating constexpr expressions. That way it doesn't overflow its own stack/buffers, nor will it hang on such evaluations. This is good enough, since the purpose of this feature is not perform heavy computations using the compiler, but rather preventing not-so-heavy computations from being performed repeatedly at run-time (and to be able to use their results in template instantiation etc.)

A theoretical compiler could statically prove that this program would have undefined behavior for any argument larger than 12, because signed overflow is UB, and it could arrive at the worst-case stack size from that.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.