What is the difference between typedef int array[3] and typedef int(array)[3]?

Viewed 1834

I recently came across this unorthodox way to define a int array type:

typedef int(array)[3];

At first I thought it was an array of function pointers but then I realized that the * and the () were missing, so by looking into the code I deduced the type array was a int[3] type instead. I normally would declare this type as:

typedef int array[3];

Unless I'm mistaken that they are not the same thing, what is the advantage of doing so in the former way other than to make them look similar to a function pointer?

3 Answers

What is the difference between typedef int array[3] and typedef int(array)[3]?

They are the same.


Parentheses could be used when a pointer is being declared, with *, and result in different types. In that case, parentheses could affect the precedence of [] or int. However, this is not your case here.

These are both equivalent. The parentheses do not alter the precedence of [] or int in this case.

The tool cdecl helps to confirm this:

  • int (a)[3] gives "declare a as array 3 of int"
  • int a[3] gives "declare a as array 3 of int"

If you run this code like this:

typedef int array[6];

array arr={1,2,3,4,5,6};
for(int i=0; i<6; i++)
     cout<<arr[i]<<" ";

And now you run this code like this:

typedef int (array)[6];
array arr={1,2,3,4,5,6};
for(int i=0; i<6; i++)
     cout<<arr[i]<<" ";

Both of those two types of code it generates the same output.This proves that both are same and the parentheses have no effect.

Related