2

Today I find the following piece of code

void func(int A[const 10]) { ... }

By compiling it using gcc, I conclude that int A[const] is equivalent to int* const A instead of const int *A. I wonder why here: const is inside the brackets, why does it not modify elements of A but A itself?

user3840170
  • 26,597
  • 4
  • 30
  • 62
Fnat
  • 31
  • 3
  • Probably because a programmer would expect `const int *A` and `const int A[]` to apply constness in the same place. – user3840170 Jan 15 '22 at 10:53

2 Answers2

2

I wonder why

Because the C standard explicitly says so.

6.7.6.3 ¶ 7 A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.

Note, "qualified pointer to type", not "pointer to qualified type". The latter is expressible with the ordinary syntax const int A[10].

This syntax was invented specifically to express "a qualified pointer to type, adjusted from an array type with an optional size provided for documentation". It is only valid in function prototypes.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

Meaning of "void func(int a[const 10])"

It exactly the same as void func(int *const a). The 10 is ignored and has no meaning - in this context, it's just documentation.

int *const a is a const pointer to mutable elements.

See Constant pointer vs Pointer to constant , What is the difference between const int*, const int * const, and int const *? , Why does a C array decay to a pointer when passed with size .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111