20

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Gabriel Diego
  • 950
  • 2
  • 10
  • 22
  • mater of taste (aka opinion based). imho the first version has a better visual separation between the alias (`array`) and the aliased type (`int[3]`) – 463035818_is_not_an_ai Sep 26 '17 at 10:08
  • This is definitively a matter of taste, since the first way for me looks confusing since it looks like a function pointer at first glance. – Gabriel Diego Sep 26 '17 at 10:10
  • 2
    From a pure semantic perspective, they are the same. The only difference is that the parentheses will change how the declarator is parsed (hence the placement of an asterisk can produce different types). Everything else is just as tobi said. – StoryTeller - Unslander Monica Sep 26 '17 at 10:10
  • 2
    Use `using array = int[3];` –  Sep 26 '17 at 10:13
  • Nearly the same question, except for the `typedef`: https://stackoverflow.com/questions/45991094 – aschepler Sep 26 '17 at 11:31

3 Answers3

20

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
7

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"
Candy Gumdrop
  • 2,745
  • 1
  • 14
  • 16
-1

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.

Linkon
  • 1,058
  • 1
  • 12
  • 15
  • 8
    This can't be taken as a correct answer since they could be working the same by chance only while there could be other cases it does not. The answer is that they are the same but the reason is another than the one stated. – Gabriel Diego Sep 26 '17 at 12:12
  • 1
    Most probably i could not understand your queries properly. – Linkon Sep 26 '17 at 12:15