const and typedef of arrays in C
First, you are mistaken, the function prototypes
int doSomething(table_t t);int doSomething(int* t);
are exactly equivalent. For function parameters, the first array dimension is always rewritten as a pointer. So there is no guarantee for the size of the array that is received.
const
-qualification on arrays always applies to the base type of the array, so the two declarations
const table_t a;int const a[N];
are equivalent, and for functions parameters we have
int doSomething(const table_t t);int doSomething(int const* t);
The content of the table will be constant. Easily checked with this code.
#include<stdio.h>typedef int table_t[3];void doSomething(const table_t t){ t++; //No error, it's a non-const pointer. t[1]=3; //Error, it's a pointer to const.}int main(){ table_t t={1,2,3}; printf("%d %d %d %ld",t[0],t[1],t[2],sizeof(t)); t[1]=5; doSomething(t); return 0;}
Array types and pointer types are not 100% equivalent, even in this context where you do ultimately get a pointer type for the function parameter. Your mistake is in assuming that const
would have acted the same way if it were a pointer type.
To expand on ARBY's example:
typedef int table_t[3];typedef int *pointer_t;void doSomething(const table_t t){ t++; //No error, it's a non-const pointer. t[1]=3; //Error, it's a pointer to const.}void doSomethingElse(const pointer_t t){ t++; //Error, it's a const pointer. t[1]=3; //No error, it's pointer to plain int}
It does act similarly to const int *
, but const pointer_t
is instead equivalent to int * const
.
(Also, disclaimer, user-defined names ending with _t are not allowed by POSIX, they're reserved for future expansion)