In C, it's possible to typedef
an array, using this construction :
typedef int table_t[N];
Here, table_t
is now defined as an array of N int
. Any variable declared such as table_t t;
will now behave as a normal array of int
.
The point of such construction is to be used as an argument type in a function, such as :
int doSomething(table_t t);
A relatively equivalent function prototype could have been :
int doSomething(int* t);
The merit of the first construction is that it enforces N
as the size of the table. In many circumstances, it's safer to enforce this property, rather than relying on the programmer to properly figure out this condition.
Now it's all good, except that, in order to guarantee that the content of table will not be modified, it's necessary to use the const
qualifier.
The following statement is relatively simple to understand :
int doSomething(const int* t);
Now, doSomething
guarantee that it will not modify the content of the table passed as a pointer.
Now, what about this almost equivalent construction ? :
int doSomething(const table_t t);
What is const
here ? the content of the table, or the pointer to the table ?
If it's the pointer which is const
, is there another way (C90 compatible) to retain the ability to define the size of the table and to tell that its content will be const ?
Note that it's also necessary sometimes to modify the content of the table, so the const
property cannot be embedded into the typedef definition.
[Edit] Thanks for the excellent answers received so far. To summarize :
- The initial assumption of typedef enforcing size N was completely wrong. It basically behaves the same as a normal pointer.
- The
const
property will also behave the same as if it was a pointer (in stark contrast with a typedef to a pointer type, as underlined by @random below) - To enforce a size (which was not the initial question, but end up being quite important now...), see Jonathan's answer