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 :
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) In C programming language, typedef is also used with arrays.
Syntax. Note that a typedef declaration does not create types. It creates synonyms for existing types, or names for types that could be specified in other ways.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With