Persistent Elements vs. Permanent Array

Everyone knows how to declare an array with constant elements:

const int a[10];

Apparently, you can also declare an array, which is itself a constant, through typedef:

typedef int X[10];
const X b;

From a technical and practical point of view, aand bhave the same type or different types?

+4
source share
3 answers

Apparently, you can also declare an array, which in itself is a constant

Nope. In N1256, §6.7.3 / 8:

If an array type specification includes qualifiers of any type, the element type has that qualification, not the array type. 118)

Footnote 118 further states:

typedefs.

+4

, clang -. const, "".

clang const int [10]. typedef int const[10]. .

Coliru .

+4

Perform some tests:

typedef int X[10];

#define typeinfo(t) _Generic((t), \
  X: "int X[10]", \
  int: "int", \
  int *: "int *", \
  const int *: "const int *", \
  default: "not" \
  )

int main(void) {
  const int a[10];
  const X b;

  printf("%zu\n", sizeof (const int *));
  puts(typeinfo(a));
  puts(typeinfo(b));
  printf("%zu\n", sizeof a);
  printf("%zu\n", sizeof b);
  puts(typeinfo(a[0]));
  puts(typeinfo(b[0]));
  printf("%zu\n", sizeof a[0]);
  printf("%zu\n", sizeof b[0]);
}

Output

4
const int *
const int *
40
40
int
int
4
4

Both are the same size and both are converted to the same type when passed as an argument. Also not a pointer. Both are arrays.

Code analysis and testing are of the same type.

+1
source

All Articles