Daria
Daria

Reputation: 79

Why does GCC accept `foo[0]` but not `*foo` as a constant?

Given the following code:

int main() {
    int constexpr foo[1] = { 4 };
    static int i = foo[0];
    static int j = *foo;
}

gcc14 -std=c23 gives:

x.c: In function 'main':
x.c:4:20: error: initializer element is not constant
    4 |     static int j = *foo;
      |                    ^

Why is the line above (static int i = foo[0];) accepted, but this one (static int j = *foo;) is an error?

C23 6.5.3.2p2 says "The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))."

This would suggest that foo[0] is identical to *(foo+0) is identical to *foo?

My expectation is both lines would be either accepted or rejected. Clang accepts both.

Upvotes: 7

Views: 143

Answers (0)

Related Questions