找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 277|回复: 1

Question 6.4:If they're so different,why are they interchangeable as function formal parameters?

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-9 10:19:33 | 显示全部楼层 |阅读模式

Q: If they're so different, then why are array and pointer declarations interchangeable as function formal parameters?
A: It's supposed to be a convenience.
Since arrays decay immediately into pointers, an array is never actually passed to a function. You can pretend that a function receives an array as a parameter, and illustrate it by declaring the corresponding parameter as an array:
                  void f(char a[])
                   { ... }
Interpreted literally, this declaration would have no use, so the compiler turns around and pretends that you'd written a pointer declaration, since that's
what the function will in fact receive:
                    void f(char *a)
                    { ... }
There's nothing particularly wrong with talking about a function as if it ``receives'' an array, if the function is traditionally used to operate on arrays, or if the parameter is naturally treated within the function as an array.

This conversion of array-like declarators into pointers holds only within function formal parameter declarations, nowhere else. If the conversion bothers
you, you're under no compulsion to make use of it; many programmers have concluded that the confusion it causes outweighs the small advantage of having the declaration ``look like'' the call or the uses within the function. (Note that the conversion happens only once; something like char a2[][] won't work. See questions 6.18 and 6.19.)

See also question 6.21.

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-9 10:59:16 | 显示全部楼层
问题:如果他们是如此的不同,那么为什么当他们作为函数的形式参数的声明的时候是可以互换的呢?
回答:这被认为是一种便利的方法。
      由于数组会立即退化为指针,那么数组也从来不会传递给一个函数。你可以假设函数接受数组作为参数,因为在函数中可能用相应的参数来作为数组使用的:
       void f(char a[])
             { ... }
从字面上来解释,这个生命就没有什么用处,因此编译器会认为你写了一个指针的声明,实际上函数将会接受的是这样的:
       void f(char *a)
             { ... }
实际上,如果这个函数是传统的用来操作数组或者是在函数中参数也是作为数组使用的,那么我们所说一个函数接受的是一个数组作为参数也没有什么错的。
这种类似数组的声明转换为指针只是在作为函数的形式参数的时候有用,在其他地方无效。如果这种转换让你困惑,那你可以不使用它;许多的程序员已经得出了结论:它导致的困惑将会比我们用“类似”的声明调用或者在函数中使用所得实惠占得比重大得多(注意这种转换只发生一次;像char a2[][]就无效了。参考问题6.18和6.19)。
参考问题6.21。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-1 04:38 , Processed in 0.068212 second(s), 19 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表