• 3766阅读
  • 1回复

Question 6.4:If they're so different,why are they interchangeable as function formal parameters? [复制链接]

上一主题 下一主题
离线那个谁
 

只看楼主 倒序阅读 使用道具 楼主  发表于: 2013-07-09
— 本帖被 tyrone2497谁 执行加亮操作(2013-07-16) —

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.
离线那个谁

只看该作者 沙发  发表于: 2013-07-09
问题:如果他们是如此的不同,那么为什么当他们作为函数的形式参数的声明的时候是可以互换的呢?
回答:这被认为是一种便利的方法。
      由于数组会立即退化为指针,那么数组也从来不会传递给一个函数。你可以假设函数接受数组作为参数,因为在函数中可能用相应的参数来作为数组使用的:
       void f(char a[])
             { ... }
从字面上来解释,这个生命就没有什么用处,因此编译器会认为你写了一个指针的声明,实际上函数将会接受的是这样的:
       void f(char *a)
             { ... }
实际上,如果这个函数是传统的用来操作数组或者是在函数中参数也是作为数组使用的,那么我们所说一个函数接受的是一个数组作为参数也没有什么错的。
这种类似数组的声明转换为指针只是在作为函数的形式参数的时候有用,在其他地方无效。如果这种转换让你困惑,那你可以不使用它;许多的程序员已经得出了结论:它导致的困惑将会比我们用“类似”的声明调用或者在函数中使用所得实惠占得比重大得多(注意这种转换只发生一次;像char a2[][]就无效了。参考问题6.18和6.19)。
参考问题6.21。
快速回复
限100 字节
如果您在写长篇帖子又不马上发表,建议存为草稿
 
上一个 下一个