[vox-tech] C question: global vs local const

Micah Cowan vox-tech@lists.lugod.org
Thu, 17 Jan 2002 17:28:04 -0800


On Thu, Jan 17, 2002 at 03:04:38PM -0800, Peter Jay Salzman wrote:
> when ratio and K are defined externally, gcc complains about a
> non-constant initializer:
> 
>    const double ratio = 2.0L;
>    const double K = ratio;
>    
>    int main(void)
>    {
>       return 0;
>    }
> 
> however, when defined as local variables, there's no problem.
> 
>    int main(void)
>    {
>       const double ratio = 2.0L;
>       const double K = ratio;
>    
>       return 0;
>    }
> 
> why isn't const being honored for the global variable version?

C isn't C++ - this would work fine in C++; however, in C, "const"
doesn't imply that the variable can be used just like a literal
constant.  It's only a means of telling the compiler that you promise
not to change it.

This isn't an issue when they're defined locally, since non-static
initializers don't have to be constant-expressions.

Micah