7

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 ?

4
  • 1
    but you're cool with using this order when defining an array: int arr[10]? :) Commented Jun 13, 2014 at 1:28
  • 1
    Reading the standard; [] comes after the designator, which is intArray in your example, to declare an array. Commented Jun 13, 2014 at 1:32
  • 2
    It is exactly the same as declaring a variable, except stick typedef on the front and it means the variable name becomes the name of the type alias. Commented Jun 13, 2014 at 1:44
  • 1
    It is just a convention of C. It is sometimes referred to as 'declaration mimics use' (try a Google search on 'C language type declaration mimics use'). Commented Jun 13, 2014 at 1:47

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Because that's how the language was defined. My guess is that, in part, it is so that what goes into a typedef follows the same rules as a normal variable declaration, except that the name is the name of the type instead of a variable (and thus that part of the parser can be re-used).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.