0

I have this somewhat complex value (in that it results from combining multiple other values in some mathematically non-trivial way) which however only ever needs to be calculated once in the whole program execution. I tried to make them all static const.

But the compiler complains that my inputs to my complex value must "have a constant value" - which they obviously do at compile time.

In this example, I want to compute c from a and b once and for all. But the compiler complains that, in the assignment of c, a and b must "have a constant value" - which they quite obviously do (seems to me).

void foo(void)
{
    static const int a = 10, b = 2;
    static const int c = a/b;
}
Charles
  • 988
  • 1
  • 11
  • 28
  • 1
    Does this answer your question? [Why in C a const object is not a compile-time constant expression?](https://stackoverflow.com/questions/40062767/why-in-c-a-const-object-is-not-a-compile-time-constant-expression) – Eugene Sh. Oct 01 '21 at 13:40
  • We'd probably need more context, but just `static int c = a/b;` (for example) would mean that the initialization is performed only once ... if that's inside a function, then it would be done the first time that function is entered. – Adrian Mole Oct 01 '21 at 13:41
  • Works just fine on [godbolt](https://godbolt.org/z/9c1P5zrrx)? – Mgetz Oct 01 '21 at 13:55
  • @Mgetz Compilers might chose to "extend" their understanding of what to consider a compile-time constant. – Eugene Sh. Oct 01 '21 at 14:00
  • @EugeneSh. possibly and if this was `gnu89` mode I'd agree. But I deliberately set the mode for a reason. So either it's a GCC bug or allowed behavior. In theory `C89` should disable extensions for conformance. That said I don't disagree that `const` in C is more of a suggestion and a programmer aid than anything useful (unfortunately). – Mgetz Oct 01 '21 at 14:04
  • 1
    @Mgetz I think the C standard is not very specific on what the "constant expression" is. The only clear requirement is that it can be evaluated at the translation time: [Constant Expressions](http://port70.net/~nsz/c/c11/n1570.html#6.6) Moreover, per [6.6p10](http://port70.net/~nsz/c/c11/n1570.html#6.6p10) it says "*An implementation may accept other forms of constant expressions.*", also [6.6 note 118](http://port70.net/~nsz/c/c11/n1570.html#note118) is giving `static int i = 2 || 1 / 0;` as a valid constant expression. – Eugene Sh. Oct 01 '21 at 14:11
  • note that most compilers support constant folding thus your expression is likely compiled into a constant. What is the complex expression that you battle with? – tstanisl Oct 01 '21 at 14:40

1 Answers1

0

Variables that are declared const are not considered constants in C, so the expression a/b is not considered constant.

The simplest way to handle this is to assign the value in main at program startup, although it means the global can't be const.

dbush
  • 205,898
  • 23
  • 218
  • 273