Skip to content

Instantly share code, notes, and snippets.

@chai2010
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save chai2010/9095218191544251d5f8 to your computer and use it in GitHub Desktop.

Select an option

Save chai2010/9095218191544251d5f8 to your computer and use it in GitHub Desktop.
Tab和Space的缩进问题

作为一个Gopher, 当然是首选 Tab 缩进.

对于C++来说, 有些不理想的编码风格导致会出现缩进不是Tab整数倍的情形:

https://code.google.com/p/protobuf/source/browse/trunk/src/google/protobuf/descriptor.cc#518

  // Find symbols.  These return a null Symbol (symbol.IsNull() is true)
  // if not found.
  inline Symbol FindNestedSymbol(const void* parent,
                                 const string& name) const;
  inline Symbol FindNestedSymbolOfType(const void* parent,
                                       const string& name,
                                       const Symbol::Type type) const;

https://code.google.com/p/protobuf/source/browse/trunk/src/google/protobuf/descriptor.cc#576

DescriptorPool::Tables::Tables()
    // Start some hash_map and hash_set objects with a small # of buckets
    : known_bad_files_(3),
      known_bad_symbols_(3),
      extensions_loaded_from_db_(3),
      symbols_by_name_(3),
      files_by_name_(3) {}

这种代码全部采用空格缩进可以保证在不同编辑器环境格式一致(主要是缩进对齐). 产生的原因是参数部分的缩进不是Tab宽度的整数倍(第一个就受到函数名字长度的影响). 因此, 最好回避这些不稳定的缩进因素.

其实只要增加一条规则就可以回避这个问题(缩进不是Tab整数倍):

  • 每一行的前导空格必须以 Tab 缩进!

当然对于前面的风格, 会出现参数没对齐的情形.

我们可以采用 Gopher 的写法:

// Find symbols.  These return a null Symbol (symbol.IsNull() is true)
// if not found.
inline Symbol FindNestedSymbol(
	const void* parent,
	const string& name
) const;
inline Symbol FindNestedSymbolOfType(
	const void* parent,
	const string& name,
	const Symbol::Type type
) const;

...

DescriptorPool::Tables::Tables():
	// Start some hash_map and hash_set objects with a small # of buckets
	known_bad_files_(3),
	known_bad_symbols_(3),
	extensions_loaded_from_db_(3),
	symbols_by_name_(3),
	files_by_name_(3)
{
	// ...
}

第一测参数就开始换行缩进. 将 (...) 当作 {...} 代码段来写.

当然, 有个不太理想的地方是, 最后一个参数末尾要少写一个逗号.

总结的Tab的使用规则:

  1. 前导空白字符, 只能使用 Tab
  2. 非前导空白字符, 禁止用 Tab

这样就不用再纠结用Tab导致不对齐的问题了.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment