foo/src/bar/baz.h
in
project foo
should have the following
guard:
-#ifndef FOO_BAR_BAZ_H_ +#ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... @@ -296,7 +297,7 @@ function, or template without an associated definition. Replacing an#include
with a forward declaration can silently change the meaning of code: -// b.h: +// b.h: struct B {}; struct D : B {}; @@ -415,7 +416,7 @@ directory without use of UNIX directory shortcutsgoogle-awesome-project/src/base/logging.h
should be included as: -#include "base/logging.h" +#include "base/logging.h"In
might look like this: -dir/foo.cc
or @@ -476,7 +477,7 @@ rely onfoo.h
's includes).#include "foo/server/fooserver.h" +#include "foo/server/fooserver.h" #include <sys/types.h> #include <unistd.h> @@ -494,7 +495,7 @@ conditional includes. Such code can put conditional includes after other includes. Of course, keep your system-specific code small and localized. Example: -#include "foo/public/fooserver.h" +#include "foo/public/fooserver.h" #include "base/port.h" // For LANG_CXX11. @@ -545,7 +546,7 @@ can continue to refer toFoo
without the prefix. the enclosing scope. Consider the following snippet, for example: -namespace X { +namespace X { inline namespace Y { void foo(); } // namespace Y @@ -589,7 +590,7 @@ namespaces, this can add a lot of clutter. gflags definitions/declarations and forward declarations of classes from other namespaces. -// In the .h file +// In the .h file namespace mynamespace { // All declarations are within the namespace scope. @@ -603,7 +604,7 @@ class MyClass { } // namespace mynamespace-// In the .cc file +// In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. @@ -617,7 +618,7 @@ void MyClass::Foo() {More complex
-.cc
files might have additional details, like flags or using-declarations.#include "a.h" +#include "a.h" DEFINE_FLAG(bool, someflag, false, "dummy flag"); @@ -643,7 +644,7 @@ using ::foo::bar;
You may not use a using-directive to make all names from a namespace available.
-// Forbidden -- This pollutes the namespace. +// Forbidden -- This pollutes the namespace. using namespace foo;
// Shorten access to some commonly used names in .cc files. +// Shorten access to some commonly used names in .cc files. namespace baz = ::foo::bar::baz;-// Shorten access to some commonly used names (in a .h file). +// Shorten access to some commonly used names (in a .h file). namespace librarian { namespace impl { // Internal, not part of the API. namespace sidetable = ::pipeline_diagnostics::sidetable; @@ -706,7 +707,7 @@ Do not use internal linkage in.h
files.Format unnamed namespaces like named namespaces. In the terminating comment, leave the namespace name empty:
-namespace { +namespace { ... } // namespace@@ -747,7 +748,7 @@ Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. For a headermyproject/foo_bar.h
, for example, write -namespace myproject { +namespace myproject { namespace foo_bar { void Function1(); void Function2(); @@ -755,7 +756,7 @@ void Function2(); } // namespace myprojectinstead of
-namespace myproject { +namespace myproject { class FooBar { public: static void Function1(); @@ -789,19 +790,19 @@ declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.: -int i; +int i; i = f(); // Bad -- initialization separate from declaration.-int j = g(); // Good -- declaration has initialization. +int j = g(); // Good -- declaration has initialization.-std::vector<int> v; +std::vector<int> v; v.push_back(1); // Prefer initializing using brace initialization. v.push_back(2);-std::vector<int> v = {1, 2}; // Good -- v starts initialized. +std::vector<int> v = {1, 2}; // Good -- v starts initialized.Variables needed for
-if
,while
@@ -809,7 +810,7 @@ andfor
statements should normally be declared within those statements, so that such variables are confined to those scopes. E.g.:while (const char* p = strchr(str, '/')) str = p + 1; +while (const char* p = strchr(str, '/')) str = p + 1;There is one caveat: if the variable is an object, its @@ -817,7 +818,7 @@ constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope.
-// Inefficient implementation: +// Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); @@ -827,7 +828,7 @@ for (int i = 0; i < 1000000; ++i) {It may be more efficient to declare such a variable used in a loop outside that loop:
-Foo f; // My ctor and dtor get called once each. +Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } @@ -1020,14 +1021,14 @@ or (since C++11) a conversion operator, to ensure that it can only be used when the destination type is explicit at the point of use, e.g. with a cast. This applies not only to implicit conversions, but to C++11's list initialization syntax: -class Foo { +class Foo { explicit Foo(int x, double y); ... }; void Func(Foo f);-Func({42, 3.14}); // Error +Func({42, 3.14}); // ErrorThis kind of code isn't technically an implicit conversion, but the language treats it as one as far asexplicit
is concerned. @@ -1185,7 +1186,7 @@ Remember to review the correctness of any defaulted operations as you would any other code, and to document that your class is copyable and/or cheaply movable if that's an API guarantee. -class Foo { +class Foo { public: Foo(Foo&& other) : field_(other.field) {} // Bad, defines only move constructor, but not operator=. @@ -1724,7 +1725,7 @@ but pointer semantics.Within function parameter lists all references must be
-const
:void Foo(const string &in, string *out); +void Foo(const string &in, string *out);In fact it is a very strong convention in Google code @@ -1775,7 +1776,7 @@ which overload is being called.
string& and overload it with another that takesconst char*
. -class MyClass { +class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); @@ -1881,13 +1882,13 @@ doubt, use overloads.C++ allows two different forms of function declarations. In the older form, the return type appears before the function name. For example:
-int foo(int x); +int foo(int x);The new form, introduced in C++11, uses the
-auto
keyword before the function name and a trailing return type after the argument list. For example, the declaration above could equivalently be written:auto foo(int x) -> int; +auto foo(int x) -> int;The trailing return type is in the function's scope. This doesn't make a difference for a simple case like
after the function's parameter list has already appeared. This is particularly true when the return type depends on template parameters. For example: -int
but it matters @@ -1907,9 +1908,9 @@ doubt, use overloads.template <class T, class U> auto add(T t, U u) -> decltype(t + u);+template <class T, class U> auto add(T t, U u) -> decltype(t + u);versus -template <class T, class U> decltype(declval<T&>() + declval<U&>()) add(T t, U u);+template <class T, class U> decltype(declval<T&>() + declval<U&>()) add(T t, U u);@@ -2061,7 +2062,7 @@ or passing a pointer or reference without transferring ownership. Prefer to usestd::unique_ptr
to make ownership transfer explicit. For example: -std::unique_ptr<Foo> FooFactory(); +std::unique_ptr<Foo> FooFactory(); void FooConsumer(std::unique_ptr<Foo> ptr);@@ -2377,7 +2378,7 @@ relationship between objects and their mocks.RTTI is useful when considering multiple abstract objects. Consider
-bool Base::Equal(Base* other) = 0; +bool Base::Equal(Base* other) = 0; bool Derived::Equal(Base* other) { Derived* that = dynamic_cast<Derived*>(other); if (that == NULL) @@ -2420,7 +2421,7 @@ such situations.Decision trees based on type are a strong indication that your code is on the wrong track.
-if (typeid(*data) == typeid(D1)) { +if (typeid(*data) == typeid(D1)) { ... } else if (typeid(*data) == typeid(D2)) { ... @@ -2910,7 +2911,7 @@ self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider: -for (unsigned int i = foo.Length()-1; i >= 0; --i) ... +for (unsigned int i = foo.Length()-1; i >= 0; --i) ...This code will never terminate! Sometimes gcc will @@ -2949,7 +2950,7 @@ problems of printing, comparisons, and structure alignment.
inttypes.h
):-// printf macros for size_t, in the style of inttypes.h +// printf macros for size_t, in the style of inttypes.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else @@ -3068,7 +3069,7 @@ problems of printing, comparisons, and structure alignment. example: -int64_t my_value = 0x123456789LL; +int64_t my_value = 0x123456789LL; uint64_t my_mask = 3ULL << 48;@@ -3101,7 +3102,7 @@ time updating the interface. As a consequence, we specifically disallow using macros in this way. For example, avoid patterns like: -class WOMBAT_TYPE(Foo) { +class WOMBAT_TYPE(Foo) { // ... public: @@ -3214,14 +3215,14 @@ to any particular variable, such as code that manages an external or internal data format where a variable of an appropriate C++ type is not convenient. -Struct data; +Struct data; memset(&data, 0, sizeof(data));-memset(&data, 0, sizeof(Struct)); +memset(&data, 0, sizeof(Struct));-if (raw_size < sizeof(int)) { +if (raw_size < sizeof(int)) { LOG(ERROR) << "compressed record not big enough for count: " << raw_size; return false; } @@ -3259,7 +3260,7 @@ especially when a variable's initialization depends on things that were declared far away. In expressions like: -auto foo = x.add_foo(); +auto foo = x.add_foo(); auto i = y.Find(key);@@ -3332,7 +3333,7 @@ and.second
(often const-ref).In C++03, aggregate types (arrays and structs with no constructor) could be initialized with braced initializer lists.
-struct Point { int x; int y; }; +struct Point { int x; int y; }; Point p = {1, 2};@@ -3341,7 +3342,7 @@ be created with a braced initializer list, known as a braced-init-list in the C++ grammar. Here are a few examples of its use. -// Vector takes a braced-init-list of elements. +// Vector takes a braced-init-list of elements. std::vector<string> v{"foo", "bar"}; // Basically the same, ignoring some small technicalities. @@ -3369,7 +3370,7 @@ TestFunction2({1, 2, 3}); that takestd::initializer_list<T>
, which is automatically created from braced-init-list: -class MyType { +class MyType { public: // std::initializer_list references the underlying init list. // It should be passed by value. @@ -3388,7 +3389,7 @@ MyType m{2, 3, 5, 7}; constructors of data types, even if they do not havestd::initializer_list<T>
constructors. -double d{1.23}; +double d{1.23}; // Calls ordinary constructor as long as MyOtherType has no // std::initializer_list constructor. class MyOtherType { @@ -3405,10 +3406,10 @@ MyOtherType m{"b"}; local variable. In the single element case, what this means can be confusing. -auto d = {1.23}; // d is a std::initializer_list<double> +auto d = {1.23}; // d is a std::initializer_list<double>-auto d = double{1.23}; // Good -- d is a double, not a std::initializer_list. +auto d = double{1.23}; // Good -- d is a double, not a std::initializer_list.See Braced_Initializer_List_Format for formatting.
@@ -3430,7 +3431,7 @@ when the lambda will escape the current scope. function objects. They're often useful when passing functions as arguments. For example: -std::sort(v.begin(), v.end(), [](int x, int y) { +std::sort(v.begin(), v.end(), [](int x, int y) { return Weight(x) < Weight(y); });@@ -3440,7 +3441,7 @@ explicitly by name, or implicitly using a default capture. Explicit captures require each variable to be listed, as either a value or reference capture: -int weight = 3; +int weight = 3; int sum = 0; // Captures `weight` by value and `sum` by reference. std::for_each(v.begin(), v.end(), [weight, &sum](int x) { @@ -3452,7 +3453,7 @@ std::for_each(v.begin(), v.end(), [weight, &sum](int x) { Default captures implicitly capture any variable referenced in the lambda body, includingthis
if any members are used: -const std::vector<int> lookup_table = ...; +const std::vector<int> lookup_table = ...; std::vector<int> indices = ...; // Captures `lookup_table` by reference, sorts `indices` by the value // of the associated element in `lookup_table`. @@ -3510,7 +3511,7 @@ wrapperstd::function
. described below.Prefer explicit captures if the lambda may escape the current scope. For example, instead of: - { +{ Foo foo; ... executor->Schedule([&] { Frobnicate(foo); }) @@ -3523,7 +3524,7 @@ For example, instead of: // and the enclosing object could have been destroyed.prefer to write: -{ +{ Foo foo; ... executor->Schedule([&foo] { Frobnicate(foo); }) @@ -3828,7 +3829,7 @@ which is unaffected by this prohibition.If you want to use the standard hash containers anyway, you will need to specify a custom hasher for the key type, e.g.
-std::unordered_map<MyKeyType, Value, MyKeyTypeHasher> my_map; +std::unordered_map<MyKeyType, Value, MyKeyTypeHasher> my_map;Consult with the type's owners to see if there is an existing hasher that you can use; otherwise work with them to provide one, @@ -3981,7 +3982,7 @@ guide, the following C++11 features may not be used:
-There are several ways to create names that are aliases of other entities:
-typedef Foo Bar; +typedef Foo Bar; using Bar = Foo; using other_namespace::Foo;@@ -4031,7 +4032,7 @@ implementation retain some degree of freedom to change the alias.For example, these aliases document how they are intended to be used in client code:
-namespace a { +namespace a { // Used to store field measurements. DataPoint may change from Bar* to some internal type. // Client code should treat it as an opaque pointer. using DataPoint = foo::bar::Bar*; @@ -4043,7 +4044,7 @@ using TimeSeries = std::unordered_set<DataPoint, std::hash<DataPoint>,These aliases don't document intended use, and half of them aren't meant for client use:
-namespace a { +namespace a { // Bad: none of these say how they should be used. using DataPoint = foo::bar::Bar*; using std::unordered_set; // Bad: just for local convenience @@ -4055,7 +4056,7 @@ typedef unordered_set<DataPoint, hash<DataPoint>, DataPointComparator&gHowever, local convenience aliases are fine in function definitions, private sections of classes, explicitly marked internal namespaces, and in .cc files:
-// In a .cc file +// In a .cc file using std::unordered_set;@@ -4093,12 +4094,12 @@ that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word. -int price_count_reader; // No abbreviation. +int price_count_reader; // No abbreviation. int num_errors; // "num" is a widespread convention. int num_dns_connections; // Most people know what "DNS" stands for.-int n; // Meaningless. +int n; // Meaningless. int nerr; // Ambiguous abbreviation. int n_comp_conns; // Ambiguous abbreviation. int wgc_connections; // Only your group knows what this stands for. @@ -4176,7 +4177,7 @@ enums, and type template parameters — have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example: -// classes and structs +// classes and structs class UrlTable { ... class UrlTableTester { ... struct UrlTableProperties { ... @@ -4209,11 +4210,11 @@ structs) additionally have trailing underscores. For instance:For example:
-string table_name; // OK - uses underscore. +string table_name; // OK - uses underscore. string tablename; // OK - all lowercase.-string tableName; // Bad - mixed case. +string tableName; // Bad - mixed case.Class Data Members
@@ -4222,7 +4223,7 @@ string tablename; // OK - all lowercase. named like ordinary nonmember variables, but with a trailing underscore. -class TableInfo { +class TableInfo { ... private: string table_name_; // OK - underscore at end. @@ -4237,7 +4238,7 @@ trailing underscore. are named like ordinary nonmember variables. They do not have the trailing underscores that data members in classes have. -struct UrlTableProperties { +struct UrlTableProperties { string name; int num_entries; static Pool<UrlTableProperties>* pool; @@ -4259,7 +4260,7 @@ versus a class. by mixed case. For example:const int kDaysInAWeek = 7; +const int kDaysInAWeek = 7;@@ -4288,7 +4289,7 @@ Case" or "Pascal case"). Such names should not have underscores. Prefer to capitalize acronyms as single words (i.e.StartRpc()
, notStartRPC()
). -AddTableEntry() +AddTableEntry() DeleteUrl() OpenFileOrDie()@@ -4368,7 +4369,7 @@ is also acceptable to name them likeAlternateUrlTableErrors
), is a type, and therefore mixed case. -enum UrlTableErrors { +enum UrlTableErrors { kOK = 0, kErrorOutOfMemory, kErrorMalformedInput, @@ -4408,7 +4409,7 @@ of macros; in general macros should not be used. However, if they are absolutely needed, then they should be named with all capitals and underscores. -#define ROUND(x) ... +#define ROUND(x) ... #define PI_ROUNDED 3.0@@ -4524,7 +4525,7 @@ comment that describes what it is for and how it should be used.-// Iterates over the contents of a GargantuanTable. +// Iterates over the contents of a GargantuanTable. // Example: // GargantuanTableIterator* iter = table->NewIterator(); // for (iter->Seek("foo"); !iter->done(); iter->Next()) { @@ -4601,7 +4602,7 @@ declaration:Here is an example:
-// Returns an iterator for this table. It is the client's +// Returns an iterator for this table. It is the client's // responsibility to delete the iterator when it is done with it, // and it must not use the iterator once the GargantuanTable object // on which the iterator was created has been deleted. @@ -4623,7 +4624,7 @@ completely obvious. Notice below that it is not necessary to say "returns false otherwise" because this is implied. -// Returns true if the table cannot hold any more entries. +// Returns true if the table cannot hold any more entries. bool IsTableFull();@@ -4687,7 +4688,7 @@ num_events_;), no comment is needed. of sentinel values, such as nullptr or -1, when they are not obvious. For example: -private: +private: // Used to bounds-check table accesses. -1 means // that we don't yet know how many entries the table has. int num_total_entries_; @@ -4699,7 +4700,7 @@ obvious. For example: are, what they are used for, and (if unclear) why it needs to be global. For example: -// The total number of tests cases that we run through in this regression test. +// The total number of tests cases that we run through in this regression test. const int kNumTestCases = 6;@@ -4719,7 +4720,7 @@ non-obvious, interesting, or important parts of your code.Tricky or complicated code blocks should have comments before them. Example:
-// Divide result by two, taking into account that x +// Divide result by two, taking into account that x // contains the carry from the add. for (int i = 0; i < result->size(); i++) { x = (x << 8) + (*result)[i]; @@ -4734,7 +4735,7 @@ for (int i = 0; i < result->size(); i++) { at the end of the line. These end-of-line comments should be separated from the code by 2 spaces. Example: -// If we have enough memory, mmap the data portion too. +// If we have enough memory, mmap the data portion too. mmap_budget = max<int64>(0, mmap_budget - index_->length()); if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) return; // Error already logged. @@ -4748,7 +4749,7 @@ returns.If you have several comments on subsequent lines, it can often be more readable to line them up:
-DoSomething(); // Comment here so the comments line up. +DoSomething(); // Comment here so the comments line up. DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment. { // One space before comment when opening a new scope is allowed, // thus the comment lines up with the following comments and code. @@ -4796,13 +4797,13 @@ one of the following remedies: Consider the following example: -// What are these arguments? +// What are these arguments? const DecimalNumber product = CalculateProduct(values, 7, false, nullptr);versus:
-ProductOptions options; +ProductOptions options; options.set_precision_decimals(7); options.set_use_cache(ProductOptions::kDontUseCache); const DecimalNumber product = @@ -4818,7 +4819,7 @@ the code does what it does, or make the code self describing. Compare this: -// Find the element in the vector. <-- Bad: obvious! +// Find the element in the vector. <-- Bad: obvious! auto iter = std::find(v.begin(), v.end(), element); if (iter != v.end()) { Process(element); @@ -4827,7 +4828,7 @@ if (iter != v.end()) { To this: -// Process "element" unless it was already processed. +// Process "element" unless it was already processed. auto iter = std::find(v.begin(), v.end(), element); if (iter != v.end()) { Process(element); @@ -4837,7 +4838,7 @@ if (iter != v.end()) { Self-describing code doesn't need a comment. The comment from the example above would be obvious: -if (!IsAlreadyProcessed(element)) { +if (!IsAlreadyProcessed(element)) { Process(element); }@@ -4896,7 +4897,7 @@ name that is given.-@@ -5219,11 +5220,11 @@ lists like other comma-separated lists.// TODO(kl@gmail.com): Use a "*" here for concatenation operator. +// TODO(kl@gmail.com): Use a "*" here for concatenation operator. // TODO(Zeke) change this to use relations. // TODO(bug 12345): remove the "Last visitors" feature@@ -5104,7 +5105,7 @@ not fit on a single line as you would wrap arguments in aFunctions look like this:
-ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) { +ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) { DoSomething(); ... } @@ -5112,7 +5113,7 @@ not fit on a single line as you would wrap arguments in aIf you have too much text to fit on one line:
-ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2, +ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2, Type par_name3) { DoSomething(); ... @@ -5121,7 +5122,7 @@ not fit on a single line as you would wrap arguments in aor if you cannot fit even the first parameter:
-ReturnType LongClassName::ReallyReallyReallyLongFunctionName( +ReturnType LongClassName::ReallyReallyReallyLongFunctionName( Type par_name1, // 4 space indent Type par_name2, Type par_name3) { @@ -5171,7 +5172,7 @@ not fit on a single line as you would wrap arguments in aUnused parameters that are obvious from context may be omitted:
-class Foo { +class Foo { public: Foo(Foo&&); Foo(const Foo&); @@ -5183,7 +5184,7 @@ not fit on a single line as you would wrap arguments in aUnused parameters that might not be obvious should comment out the variable name in the function definition:
-class Shape { +class Shape { public: virtual void Rotate(double radians) = 0; }; @@ -5196,7 +5197,7 @@ class Circle : public Shape { void Circle::Rotate(double /*radians*/) {}-// Bad - if someone wants to implement later, it's not clear what the +// Bad - if someone wants to implement later, it's not clear what the // variable means. void Circle::Rotate(double) {}@@ -5204,7 +5205,7 @@ void Circle::Rotate(double) {}Attributes, and macros that expand to attributes, appear at the very beginning of the function declaration or definition, before the return type:
-MUST_USE_RESULT bool IsOK(); +MUST_USE_RESULT bool IsOK();For by-reference captures, do not leave a space between the ampersand (&) and the variable name.
-int x = 0; +int x = 0; auto x_plus_n = [&x](int n) -> int { return x + n; }Short lambdas may be written inline as function arguments.
-std::set<int> blacklist = {7, 8, 9}; +std::set<int> blacklist = {7, 8, 9}; std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1}; digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) { return blacklist.find(i) != blacklist.end(); @@ -5247,7 +5248,7 @@ on each line where appropriate.Function calls have the following format:
-bool result = DoSomething(argument1, argument2, argument3); +bool result = DoSomething(argument1, argument2, argument3);If the arguments do not all fit on one line, they @@ -5255,13 +5256,13 @@ should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do not add spaces after the open paren or before the close paren:
-bool result = DoSomething(averyveryveryverylongargument1, +bool result = DoSomething(averyveryveryverylongargument1, argument2, argument3);Arguments may optionally all be placed on subsequent lines with a four space indent:
-if (...) { +if (...) { ... ... if (...) { @@ -5285,13 +5286,13 @@ better addressed with the following techniques. readability due to the complexity or confusing nature of the expressions that make up some arguments, try creating variables that capture those arguments in a descriptive name: -int my_heuristic = scores[x] * y + bases[x]; +int my_heuristic = scores[x] * y + bases[x]; bool result = DoSomething(my_heuristic, x, y, z);Or put the confusing argument on its own line with an explanatory comment:
-bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic. +bool result = DoSomething(scores[x] * y + bases[x], // Score heuristic. x, y, z);@@ -5303,7 +5304,7 @@ which is made more readable rather than a general policy.Sometimes arguments form a structure that is important for readability. In those cases, feel free to format the arguments according to that structure:
-// Transform the widget by a 3x3 matrix. +// Transform the widget by a 3x3 matrix. my_widget.Transform(x1, x2, x3, y1, y2, y3, z1, z2, z3); @@ -5325,7 +5326,7 @@ variable name), format as if the{}
were the parentheses of a function call with that name. If there is no name, assume a zero-length name. -// Examples of braced init list on a single line. +// Examples of braced init list on a single line. return {foo, bar}; functioncall({foo, bar}); std::pair<int, int> p{foo, bar}; @@ -5374,7 +5375,7 @@ writing new code, use the format that the other files in that directory or project use. If in doubt and you have no personal preference, do not add the spaces. -if (condition) { // no spaces inside parentheses +if (condition) { // no spaces inside parentheses ... // 2 space indent. } else if (...) { // The else goes on the same line as the closing brace. ... @@ -5386,7 +5387,7 @@ no personal preference, do not add the spaces.If you prefer you may add spaces inside the parentheses:
-if ( condition ) { // spaces inside parentheses - rare +if ( condition ) { // spaces inside parentheses - rare ... // 2 space indent. } else { // The else goes on the same line as the closing brace. ... @@ -5398,12 +5399,12 @@ theif
and the open parenthesis. You must also have a space between the close parenthesis and the curly brace, if you're using one. -if(condition) { // Bad - space missing after IF. +if(condition) { // Bad - space missing after IF. if (condition){ // Bad - space missing before {. if(condition){ // Doubly bad.-if (condition) { // Good - proper space after IF and before {. +if (condition) { // Good - proper space after IF and before {.Short conditional statements may be written on one @@ -5411,14 +5412,14 @@ line if this enhances readability. You may use this only when the line is brief and the statement does not use the
-else
clause.if (x == kFoo) return new Foo(); +if (x == kFoo) return new Foo(); if (x == kBar) return new Bar();This is not allowed when the if statement has an
-else
:// Not allowed - IF statement on one line when there is an ELSE clause +// Not allowed - IF statement on one line when there is an ELSE clause if (x) DoThis(); else DoThat();@@ -5432,7 +5433,7 @@ projects require that anif
must always always have an accompanying brace. -if (condition) +if (condition) DoSomething(); // 2 space indent. if (condition) { @@ -5444,7 +5445,7 @@ if (condition) {if
-else
statement uses curly braces, the other part must too: -// Not allowed - curly on IF but not ELSE +// Not allowed - curly on IF but not ELSE if (condition) { foo; } else @@ -5458,7 +5459,7 @@ else { }-// Curly braces around both IF and ELSE required because +// Curly braces around both IF and ELSE required because // one of the clauses used braces. if (condition) { foo; @@ -5495,7 +5496,7 @@ case should never execute, simply-@@ -5553,7 +5554,7 @@ have trailing spaces.switch (var) { +switch (var) { case 0: { // 2 space indent ... // 4 space indent break; @@ -5517,7 +5518,7 @@ case should never execute, simplyBraces are optional for single-statement loops.
-for (int i = 0; i < kSomeNumber; ++i) +for (int i = 0; i < kSomeNumber; ++i) printf("I love you\n"); for (int i = 0; i < kSomeNumber; ++i) { @@ -5529,14 +5530,14 @@ for (int i = 0; i < kSomeNumber; ++i) {Empty loop bodies should use an empty pair of braces or
-continue
, but not a single semicolon.while (condition) { +while (condition) { // Repeat test until it returns false. } for (int i = 0; i < kSomeNumber; ++i) {} // Good - one newline is also OK. while (condition) continue; // Good - continue indicates no logic.-while (condition); // Bad - looks like part of do/while loop. +while (condition); // Bad - looks like part of do/while loop.The following are examples of correctly-formatted pointer and reference expressions:
-x = *p; +x = *p; p = &x; x = r.y; x = r->y; @@ -5573,7 +5574,7 @@ x = r->y; place the asterisk adjacent to either the type or to the variable name: -// These are fine, space preceding. +// These are fine, space preceding. char *c; const string &str; @@ -5585,10 +5586,10 @@ const string& str; It is allowed (if unusual) to declare multiple variables in the same declaration, but it is disallowed if any of those have pointer or reference decorations. Such declarations are easily misread. -// Fine if helpful for readability. +// Fine if helpful for readability. int x, y;-int x, *y; // Disallowed - no & or * in multiple declaration +int x, *y; // Disallowed - no & or * in multiple declaration char * c; // Bad - spaces on both sides of * const string & str; // Bad - spaces on both sides of &@@ -5613,7 +5614,7 @@ consistent in how you break up the lines.In this example, the logical AND operator is always at the end of the lines:
-if (this_one_thing > this_other_thing && +if (this_one_thing > this_other_thing && a_third_thing == a_fourth_thing && yet_another && last_one) { ... @@ -5647,13 +5648,13 @@ expression with parentheses.Use parentheses in
-return expr;
only where you would use them inx = expr;
.return result; // No parentheses in the simple case. +return result; // No parentheses in the simple case. // Parentheses OK to make a complex expression more readable. return (some_long_condition && another_condition);-return (value); // You wouldn't write var = (value); +return (value); // You wouldn't write var = (value); return(result); // return is not a function!@@ -5674,7 +5675,7 @@ return(result); // return is not a function!()
, and{}
; the following are all correct: -int x = 3; +int x = 3; int x(3); int x{3}; string name = "Some Name"; @@ -5691,7 +5692,7 @@ will call a default constructor if available. To force the non-std::initializer_list
constructor, use parentheses instead of braces. -std::vector<int> v(100, 1); // A vector of 100 1s. +std::vector<int> v(100, 1); // A vector of 100 1s. std::vector<int> v{100, 1}; // A vector of 100, 1.@@ -5699,7 +5700,7 @@ std::vector<int> v{100, 1}; // A vector of 100, 1. types. This can prevent some types of programming errors. -int pi(3.14); // OK -- pi == 3. +int pi(3.14); // OK -- pi == 3. int pi{3.14}; // Compile error: narrowing conversion.@@ -5718,7 +5719,7 @@ always be at the beginning of the line. of indented code, the directives should start at the beginning of the line. -// Good - directives at beginning of line +// Good - directives at beginning of line if (lopsided_score) { #if DISASTER_PENDING // Correct -- Starts at beginning of line DropEverything(); @@ -5730,7 +5731,7 @@ beginning of the line. }-// Bad - indented directives +// Bad - indented directives if (lopsided_score) { #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line DropEverything(); @@ -5755,7 +5756,7 @@ comments, see Class Comments for a discussion of what comments are needed) is: -class MyClass : public OtherClass { +class MyClass : public OtherClass { public: // Note the 1 space indent! MyClass(); // Regular 2 space indent. explicit MyClass(int var); @@ -5815,7 +5816,7 @@ with subsequent lines indented four spaces.The acceptable formats for initializer lists are:
-// When everything fits on one line: +// When everything fits on one line: MyClass::MyClass(int var) : some_var_(var) { DoSomething(); } @@ -5854,7 +5855,7 @@ MyClass::MyClass(int var)Namespaces do not add an extra level of indentation. For example, use:
-namespace { +namespace { void foo() { // Correct. No extra indentation within namespace. ... @@ -5865,7 +5866,7 @@ void foo() { // Correct. No extra indentation within namespace.Do not indent within a namespace:
-namespace { +namespace { // Wrong. Indented when it should not be. void foo() { @@ -5878,7 +5879,7 @@ void foo() { // Correct. No extra indentation within namespace.When declaring nested namespaces, put each namespace on its own line.
-namespace foo { +namespace foo { namespace bar {@@ -5895,7 +5896,7 @@ trailing whitespace at the end of a line.General
-void f(bool b) { // Open braces should always have a space before them. +void f(bool b) { // Open braces should always have a space before them. ... int i = 0; // Semicolons usually have no space before them. // Spaces inside braces for braced-init-list are optional. If you use them, @@ -5924,7 +5925,7 @@ else is working on the file).Loops and Conditionals
-if (b) { // Space after the keyword in conditions and loops. +if (b) { // Space after the keyword in conditions and loops. } else { // Spaces around else. } while (test) {} // There is usually no space inside parentheses. @@ -5952,7 +5953,7 @@ switch (i) {Operators
-// Assignment operators always have spaces around them. +// Assignment operators always have spaces around them. x = 0; // Other binary operators usually have spaces around them, but it's @@ -5971,7 +5972,7 @@ if (x && !y)Templates and Casts
-// No spaces inside the angle brackets (< and >), before +// No spaces inside the angle brackets (< and >), before // <, or between >( in a cast std::vector<string> x; y = static_cast<char*>(x);