4 ms·
* Context: const and compile-time constants Constructs fully determined at compile time have some benefits. But const in C is weaker than constexpr that C++ h
by s_gourichon 3y ago
* Context: const and compile-time constants
Constructs fully determined at compile time have some benefits.
But const in C is weaker than constexpr that C++ has.
As prog-fh summarizes on
https://stackoverflow.com/questions/66144082/why-does-gcc-clang-handle-code-slightly-differently-example-given https://stackoverflow.com/questions/66144082/why-does-gcc-cl...
> "The const means « I swear that I won't change the value of this variable » (or the compiler will remind me!). But it does not mean that it could not change by another mean I don't see in this compilation unit; thus this is not exactly a constant."
One example of invalid C:
const int mysize = 2;
const int myarray[mysize];
gcc: error: variably modified ‘myarray’ at file scope
clang: warning: variable length array folded to constant array as an extension [-Wgnu-folding-constant]
const int myarray[mysize];
* Good news: C can do compile time constant structs and array with deep self-references.
Yes, in C you can define and fully declare complex data structures that are accepted as compile-time constants, including pointers to parts of itself.
See "self-contained, statically allocated, totally const data structure with backward and forward references (pointers)?" for a previous example at https://stackoverflow.com/questions/47037701/can-c-syntax-define-a-self-contained-statically-allocated-totally-const-data-s https://stackoverflow.com/questions/47037701/can-c-syntax-de...
-----------------
I used this for a game on a retro machine where such a data structure avoids code which would have been several times (perhaps 10 times) bigger: https://github.com/cpcitor/color-flood-for-amstrad-cpc/blob/master/widget_configscreen.c https://github.com/cpcitor/color-flood-for-amstrad-cpc/blob/...
Here's another take showing two variants: where overall construct is an array then a struct: https://gist.github.com/fidergo-stephane-gourichon/792c194e1b051a70995c27b5af8df92d https://gist.github.com/fidergo-stephane-gourichon/792c194e1...