Algorithm Design Manual, chapter 3, linked-list code snippet confusion

那年仲夏 提交于 2019-12-12 11:41:24

问题


I'm reading the Algorithm Design Manual and in chapter 3, the following code snippet appears. It has to do with removing an item from a linked-list. The question isn't related to data-structures, but just to a single line of code where two variables are declared I think. I've stripped the non-relevant parts of the code for brevity.

list *search_list(list *l, item_type x) {
  // This function just searches the list x
}

list *predecessor_list(list *l, item_type x) {
  // This function simply returns the predecessor of x or NULL
}

delete_list(list **l, item_type x) {
  list *p;     /* item pointer */
  list *pred;  /* predecessor pointer */

  list *search_list(), *predecessor_list(); // What are these declarations?

  p = search_list(*l,x);

  // Code to delete the node if found is here    
}

My question is in the delete_list function, specifically, the line list *search_list(), *predecessor_list();. What is happening on that line? I'm guessing it's a pointer to a function, but my understanding is you are supposed to declare the function pointer with the appropriate parameters. Also, assuming I am correct, why are those lines even needed?


回答1:


The line in question,

list *search_list(), *predecessor_list();

informs the compiler that an identifier for a function exists and what its return type is. In this context, the number and type of parameter(s) the function requires is not needed.

I agree it's a bit peculiar and not very intuitive, however, the C language supports many such peculiarities.

The link provided in a comment to your question by Dabo goes into more detail: Why does an empty declaration work for definitions with int arguments but not for float arguments?




回答2:


Those are function declarations, to inform that search_list() and predecessor_list() return list*. If you use a function before you declare it, it is implicitly declared to be ‘function returning int’. In case functions search_list() and predecessor_list() defined before delete_list you won't need those declarations.

Try to put those functions after delete_list and remove declarations, you will get conflicting types for search_list() as your compiler will assume that search_list() and predecessor_list() should return int



来源:https://stackoverflow.com/questions/22497876/algorithm-design-manual-chapter-3-linked-list-code-snippet-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!