skip to Main Content

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

vsc error

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


  1. const variable is not a constant expression.

    What is constant expression:

    An integer constant expression shall have integer type and shall
    only have operands that are integer constants, enumeration constants,
    character constants, sizeof expressions whose results are integer
    constants, and floating constants that are the immediate operands of
    casts. Cast operators in an integer constant expression shall only
    convert arithmetic types to integer types, except as part of an
    operand to the sizeof operator.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search