Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef array type in C

Tags:

arrays

c

typedef

typedef int arr[10]

I understand that the above statement defines a new name for int[10] so that

arr intArray;

is equivalent to

int intArray[10];

However, I am confused by the convention for doing this. It seems to me that

typedef int arr[10]

is confusing and a clear way to me is

typedef int[10] arr

i.e. I define the "int[10]" to be a new type called arr

However, the compiler does not accept this.

May I ask why ? Is it just a convention for C language ?

like image 232
Jing Avatar asked Jun 13 '14 01:06

Jing


1 Answers

Very early versions of C didn't have the typedef keyword. When it was added to the language (some time before 1978), it had to done in a way that was consistent with the existing grammar.

Syntactically, the keyword typedef is treated as a storage class specifier, like extern or static, even though its meaning is quite different.

So just as you might write:

static int arr[10];

you'd write:

typedef int arr[10];

Think of a typedef declaration as something similar to an object declaration. The difference is that the identifier it creates (arr in this case) is a type name rather than an object name.

like image 53
Keith Thompson Avatar answered Oct 09 '22 17:10

Keith Thompson