几个简单代码片段-- Google C++ style guide

欧洲杯,德国VS意大利。战车遇到浪漫之师,结果如何?
Who Cares!!!

开球之前,review一下近期写的代码,发现一些代码写的不是很规范。于是,重新温习一下 Google C++ style guide。

之前博客有过介绍,谷歌C++编程规范笔记,现在只是用几个简单的代码片段展示一下。

定义常量、宏定义、枚举:

// 使用下划线分隔
#define FLAG_FOO 0x0

// 要有括号
#define FLAG_BAZ (0x1 << 3)

// 对于常量,使用k
const int kStateFoo = 0;


typedef struct linked_list LinkedList;

// 枚举跟宏定义类似
typedef enum {
  MODE_FOO,
  MODE_BAR,
  MODE_BAZ,
  MODE_QUX
} Mode;

// 枚举也可以像常量一样
typedef enum {
  kStateFoo,
  kStateBar,
  kStateBaz,
  kStateQux
} State;

typedef struct sample {
  int first_field;
  bool second_field;
  Mode mode;
  State state;
  struct sample *next;
} Sample;

函数:

//注意第一个大括号的位置
bool SampleEqual(Sample *self, Sample *other) {
  // Local variables are lower_case and separated by underscores.
  if (self == NULL && other == NULL) {
    return true;
  }

  if (self == NULL || other == NULL) {
    return false;
  }

  //多行
  if (self->first_field == other->first_field &&
      self->second_field == other->second_field &&
      self->state == other->state &&
      self->mode == other->mode &&
      self->next == other->next) {
    return true;
  }

  return false;
}

//多个参数
Sample *SampleNew(int first_field,
                  bool second_field,
                  Mode mode,
                  State state,
                  Sample *next) {
  Sample *sample = (Sample *) malloc(sizeof(*sample));
  if (sample == NULL) {
    return NULL;
  }

  memset(sample, 0, sizeof(sample));
  sample->first_field = first_field;
  sample->second_field = second_field;
  sample->mode = mode;
  sample->state = state;
  sample->next = next;
  return sample;
}

Sample *SampleClone(Sample *sample) {
  if (sample == NULL) {
    return NULL;
  }

  return SampleNew(sample->first_field,
                   sample->second_field,
                   sample->mode,
                   sample->state,
                   sample->next);
}


static void SampleDoSomethingWithALongName(
    Sample *sample,
    int parameter_with_a_long_name,
    bool another_parameter,
    int another_parameter) {
  if (sample == NULL) {
    return;
  }

  bool local_variable;
  if (parameter_with_a_long_name == kStateFoo) {
    local_variable = true;
  } else {
    local_variable = false;
  }
  sample->first_parameter += another_parameter;
  sample->second_parameter |= local_variable;
}

你可能感兴趣的:(谷歌,code-style)