【问题标题】:Long function declaration line. What are the conventions for splitting it?长函数声明行。拆分它的约定是什么?
【发布时间】:2013-05-10 21:43:05
【问题描述】:

这是声明

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

我应该拆分它吗?我应该保持原样吗?也许我应该做一些不同的事情?

【问题讨论】:

  • 首先,typedef int (*cmp_func)(void *, void *);

标签: c coding-style


【解决方案1】:

这完全是口味问题,但我会喜欢以下方面的东西:

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

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

【讨论】:

    【解决方案2】:

    在 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]:cindent,默认为 C/C++ 开启。
    [2]:不确定它是在 Java、JavaScript 还是其他地方,但我之前已经看到过这个被广泛使用。

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多