[英]What is the difference between typedef int array[3] and typedef int(array)[3]?
I recently came across this unorthodox way to define a int array type: 我最近遇到了这种非正统的方式来定义一个int数组类型:
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. 起初我以为它是一个函数指针数组但后来我意识到缺少了*
和()
,所以通过查看代码我推断出类型数组是一个int[3]
类型。 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? 除非我误以为它们不是同一个东西,除了使它们看起来类似于函数指针之外,以前的方式这样做有什么好处?
What is the difference between
typedef int array[3]
andtypedef int(array)[3]
?typedef int array[3]
和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
. 在这种情况下,括号可能会影响[]
或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. 在这种情况下,括号不会改变[]
或int
的优先级。
The tool cdecl helps to confirm this: 工具cdecl有助于确认这一点:
int (a)[3]
gives "declare a as array 3 of int" int (a)[3]
给出“声明一个int的数组3” int a[3]
gives "declare a as array 3 of int" int a[3]
给出“声明一个int的数组3” 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. 这两种类型的代码都生成相同的输出。这证明两者都是相同的,括号没有效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.