Reputation: 1987
In the following code, are the const variable B, C and P calculated once during start-up of the application, or at run time (ie. every time parabolicSine is called)?
Optimising this, wondering if it'll make any difference if I pre-calculated B, C and P. (to avoid division)
Thanks.
const double B = 4.0/(float)pi;
const double C = -4.0/((float)pi*(float)pi);
const double P = 0.225;
inline double parabolicSine(double x, bool bHighPrecision = true)
{
double y = B * x + C * x * fabs(x);
if(bHighPrecision)
y = P * (y * fabs(y) - y) + y;
return y;
}
Upvotes: 1
Views: 3659
Reputation: 16777
const
variables are not required to be computed at compile time even when their definition allows it. While most compilers will likely implement it in such trivial cases, the only way to require that it be done is to make the variable a constexpr
. constexpr
generalizes the definition of constant expressions to variables and functions. In addition, it frees you from having to worry about compiler quirks and instead make it explicit that the variable value should be available at compile time.
Upvotes: 5
Reputation: 8112
Its compiler based. Consider below example.
int n=5;
int arr[n];// It works fine when compiling with gcc However ERROR : when compiling in Visual Studio.
const int n=5;
int arr[n]; //Compiles successfully in VS
Upvotes: 0
Reputation: 18974
They may not be computed at compile time, but they will be computed no more than once. (A variable only ever gets initialised once.) So there is no chance they will be evaluated on every call to ParabolicSine
.
Upvotes: 1
Reputation:
Yes, they are calculated once (compile-time), here's the disassembly from GCC:
LFE1:
.section .rdata,"dr"
.align 4
__ZL2pi:
.long 1078523331
.align 8
__ZL1B:
.long -1887771331
.long 1072980437
.align 8
__ZL1C:
.long 256041101
.long -1076234516
.align 8
__ZL1P:
.long -858993459
.long 1070386380
.align 8
Do also note that optimizations don't matter at all in this situation. It may however, be just pushed on the stack as constants when calling the function (if used once, or so, depends on compiler)
Upvotes: 1