Hello! I'm wondering if I should use const vs. static const when defining a constant local variable within a function. I use static const instead of #define for my global constants. Thanx in advance for any and all replies! -B
To add to what Disch said, the only difference between the two is how many times the variable is initialized. Statics are initialized only once. For POD types where the right-hand side is constant, you won't see any difference. ie,
1 2 3 4
void foo() {
staticconstdouble PI = 3.14;
constdouble PI = 3.14;
}
But if the right-hand side is non-trivial, you could see a performance difference:
In the first case, fib100 is computed exactly once during the lifetime of the program. In the second case, it is computed each time the foo() is called. If fibonacci() is poorly coded, this could result in a significant performance degradation.
So it really comes down to how much work it takes to do the initialization.