长函数声明行。有哪些拆分它的约定?

14

这里是声明

dll_DoublyLinkedNode *dll_search(const dll_DoublyLinkedList list, void *key, int (*compare)(void *data, void *key)){

我应该把它分开吗?还是就这样保持不变呢?也许我应该做些不同的事情?


首先,typedef int (*cmp_func)(void *, void *); - user529758
2个回答

19

这完全是个人口味问题,但我比较喜欢类似以下的风格:

dll_DoublyLinkedNode *dll_search(
  const dll_DoublyLinkedList list, 
  void *key, 
  int (*compare)(void *data, void *key)
){

此外,你可以为引用的函数指针类型进行typedef,并给它一个方便的名称。

16

在C语言中,有许多写大型函数声明的惯例。以下是一些最常见的惯例:

      /////////////////////////////
     //  Type //    Meaning    ///
    /////////////////////////////
   //  `.`  // Single space   //
  //  `-|` // Half an indent //
 //  `->` // Full indent    //
/////////////////////////////

// One line
static inline int namespace_class_method(class_t *self, a_t a, b_t b, c_t c);

// Traditional C
static inline int namespace_class_method(self, a, b, c)
..class_t *self;
..a_t a;
..b_t b;
..c_t c;
{
../* Traditional K&R C had no declarations */
}

// Line wrapping
static inline int namespace_class_method(class_t *self, a_t a,
b_t b, c_t c);

// Naive
static inline int namespace_class_method(class_t *self, a_t a,
--->b_t b, c_t c);

// Linux, VIM[1]
static inline int namespace_class_method(class_t *self, a_t a,
........b_t b, c_t c);

// GNU
static inline int
namespace_class_method(class_t *self, a_t a,
.......................b_t b, c_t c);

// Java[2]

static inline int
namespace_class_method
-|(
--->class_t *self,
--->a_t a,
--->b_t b,
--->c_t c
-|);

// Haskell style
static inline int
namespace_class_method
-|( class_t *self
-|, a_t      a
-|, b_t      b
-|, c_t      c );

选择一种并坚持下去。一致性和易读性比宗教和风格更重要。

[1]: 对于C/C++默认开启。
[2]: 我不确定它是否在Java、JavaScript或其他地方,但我之前看到过这个被广泛使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接