I am getting an error like this despite using const. Var
in this case comes from an enum. Compiling works without errors or warnings. I assume this is issue with vsc or something
This code will compile and run without errors
#include <stdio.h>
typedef union {
const char *s;
int i;
}Variable;
enum {
a = 0,
b,
Var,
};
const Variable var2 = {.i=Var};
Variable p3[][3] = {
{var2, "test", {.i=5}},
{{.i=Var}, "test2", {.i=50}}
};
int main() {
printf("%dn", p3[0][0].i);
printf("%dn", p3[1][0].i);
}
2
Answers
const
variable is not a constant expression.What is constant expression:
An initializer for an object with static storage duration, which includes file scope objects, must be a constant expression.
The C standard does not explicitly allow for
const
qualified file scope objects to be considered a constant expression. VSCode is printing an error message in the IDE because of this.However, implementations are allowed to accept other types of constant expressions. In gcc starting with version 8, a
const
qualified file scope object is in fact considered a constant expression, and thus your code compiles on that version of gcc and later. gcc versions 7.5 and earlier will report an error when trying to compile this code.