static const vs. const, when to use each

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
If the constant will be the same every time the function is called, use static const.

If the constant is only constant for the lifetime of the function and may change depending on on how/when the function is called, use const.

Usually you will want to use static const. Though in practice the compiler will likely optimize for you so it probably doesn't matter.
Last edited on
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() {
    static const double PI = 3.14;
    const double PI = 3.14;
}


But if the right-hand side is non-trivial, you could see a performance difference:

1
2
3
void foo() {
    static const unsigned long long fib100 = fibonacci( 100 );
    const unsigned long long fib100 - fibonacci( 100 );


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.

Wow! Thanks to both!
Topic archived. No new replies allowed.