Consider the following example:
#include <stdio.h>
#include <stdint.h>
struct mystruct_s {
uint16_t first;
};
typedef struct mystruct_s mystruct_t;
#define THEVALUE 5
const mystruct_t mytester = {
.first = THEVALUE,
};
struct otherstruct_s {
uint16_t initial;
};
typedef struct otherstruct_s otherstruct_t;
otherstruct_t othertester = {
.initial = mytester.first,
};
int main() {
printf("Hello, world %d!\n", othertester.initial);
return 0;
}
When I build this in https://replit.com/languages/c I get:
> clang-7 -pthread -lm -o main main.c
main.c:20:23: error: initializer element is not a
compile-time constant
.initial = mytester.first,
~~~~~~~~~^~~~~
1 error generated.
exit status 1
I was kind of hoping, that since mytester
is declared const
, and its its .first
field is initialized through a define, the compiler would have figured out that I want the same initialization applied to othertester.initial
, but apparently not.
In my actual code, gcc
was highlighting mytester
, while here clang
did in fact point to the field by highlighting, which indeed is not const - is this why I cannot initialize in this case?
Anyways, I have a similar (though much more convoluted) actual case; and while I'm aware that I can just use the define to initialize, I would really like to instead initialize via mytester.first
for readability. Is there any workaround where I can use that, without having to define a copy of mystruct_s
where the .first
field is const
?