Compile-Time Computation of String Length
To compute a string literal's length at compile time, the code snippet below utilizes a recursive function:
<code class="cpp">#include <cstdio> int constexpr length(const char* str) { return *str ? 1 + length(str + 1) : 0; } int main() { printf("%d %d", length("abcd"), length("abcdefgh")); }</code>
This function successfully computes the lengths as expected, as evidenced by the generated assembly code from clang, which shows the results being computed at compile time.
Standard Guarantee for Compile-Time Evaluation
However, it is crucial to note that the evaluation of constant expressions at compile time is not explicitly guaranteed by the standard. While the draft C standard section 5.19 does include a non-normative quote stating that constant expressions can be evaluated during translation, this does not provide a definitive guarantee.
Ensuring Compile-Time Evaluation
To ensure that a function is evaluated at compile time, Bjarne Stroustrup recommends assigning its result to a constexpr variable. This can be seen in the following example:
<code class="cpp">constexpr int len1 = length("abcd");</code>
Additionally, Bjarne Stroustrup outlines two specific cases where compile-time evaluation is guaranteed:
Therefore, for reliable compile-time evaluation, it is advisable to follow either of these two approaches.
The above is the detailed content of How Can We Guarantee Compile-Time Evaluation of String Length?. For more information, please follow other related articles on the PHP Chinese website!