I'm studying the C++ programming language and in a chapter my book introduces me the concept of constant :
A constexpr symbolic constant must be given a value that is known at compile time
What is a value known at compile time ? Why we need of them ?
In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled.
During compile time the compiler check for the syntax, semantic, and type of the code.
A Java variable is a compile-time constant if it's of a primitive type or String, declared final, initialized within its declaration, and with a constant expression. Strings are a special case on top of the primitive types because they are immutable and live in a String pool.
A compile-time constant is a value that is computed at the compilation-time. Whereas, A runtime constant is a value that is computed only at the time when the program is running. 2. A compile-time constant will have the same value each time when the source code is run.
A constant expression means an expression that can be evaluated at compile-time (i.e. before the program runs, during compilation) by the compiler.
A constant expression can be used to initialize a variable marked with constexpr
(referring to the C++11 concept). Such a variable gives the compiler the hint that it could be compile-time evaluated (and that might spare precious runtime cycles), e.g.
#include <iostream>
constexpr int factorial(int n) // Everything here is known at compile time
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}
int main(void)
{
constexpr int f = factorial(4); // 4 is also known at compile time
std::cout << f << std::endl;
return 0;
}
Example
If you don't provide a constant expression, there's no way the compiler can actually do all this job at compile-time:
#include <iostream>
constexpr int factorial(int n) // Everything here is known at compile time
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}
int main(void)
{
int i;
std::cin >> i;
const int f = factorial(i); // I really can't guess this at compile time..
// thus it can't be marked with constexpr
std::cout << f << std::endl;
return 0;
}
Example
The gain in doing compile-time extra-work instead of run-time work is performance gain since your compiled program might be able to use precomputed values instead of having to compute them from scratch each time. The more expensive the constant expression is, the bigger is the gain your program gets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With