Brian Silverman | 1a67511 | 2016-02-20 20:42:49 -0500 | [diff] [blame^] | 1 | <!DOCTYPE html> |
| 2 | <html> |
| 3 | <head> |
| 4 | <meta http-equiv="content-type" content="text/html; charset=UTF-8"> |
| 5 | <title>WPILib C++ Style Guide</title> |
| 6 | <link rel="stylesheet" type="text/css" href="include/styleguide.css"> |
| 7 | <script language="javascript" src="include/styleguide.js"></script> |
| 8 | </head> |
| 9 | <body onload="initStyleGuide();"> |
| 10 | <div id="content"> |
| 11 | <h1>WPILib C++ Style Guide (Based on the <a href=http://google-styleguide.googlecode.com/svn/trunk/cppguide.html>Google C++ Style Guide</a>)</h1> |
| 12 | <div class="horizontal_toc" id="tocDiv"></div> |
| 13 | |
| 14 | <div class="main_body"> |
| 15 | |
| 16 | <h2 class="ignoreLink" id="Background">Background</h2> |
| 17 | |
| 18 | <p><strong>This guide is a work in progress.</strong> |
| 19 | We are currently working on getting this guide updated to |
| 20 | a point where it is useful for WPILib developers to use.</p> |
| 21 | |
| 22 | <p>C++ is one of the two main languages (Java being the other) |
| 23 | used in WPILib; in order to maintain consistency and keep the |
| 24 | maintenance of the code manageable, we use this style guide.</p> |
| 25 | |
| 26 | <p>There are two main overarching purposes to this guide. The first |
| 27 | is to act as a normal C++ style guide (both in terms fo formatting |
| 28 | and programming practices) for C++ developers of WPILib. |
| 29 | The other purpose is to help Java programmers who may |
| 30 | know a moderate amount of C++ but may not be fully |
| 31 | up to date with things like C++11 and so may not even |
| 32 | realize that certain C++ features exist.</p> |
| 33 | |
| 34 | <p>This style guide is a heavily modified version of the |
| 35 | <a href=http://google-styleguide.googlecode.com/svn/trunk/cppguide.html> |
| 36 | Google C++ Style Guide</a>. The Google Style Guide has |
| 37 | a lot of good points and is a good read, but in order |
| 38 | to cut the style guide down to a more readable size and to |
| 39 | focus mroe on WPILib-specific information, we have |
| 40 | altetered the original style guide in several ways.</p> |
| 41 | |
| 42 | <p>One way in which we <em>haven't</em> done much to |
| 43 | alter the original style guide is to keep the vast |
| 44 | majority of the formatting/naming/etc. related |
| 45 | information intact. This is both so that we |
| 46 | do not have to write up our own standards and so |
| 47 | that existing tools such as clang-format and |
| 48 | the Google eclipse format configuration files |
| 49 | can work out of the box. All of these things |
| 50 | should be relatively non-controversial and do not |
| 51 | require much discussion.</p> |
| 52 | |
| 53 | <p>Where we deviate more from the original guide is |
| 54 | in the style of the code itself. At the moment (ie, |
| 55 | when we first created this modified version), we |
| 56 | deleted all of the sections of the original guide |
| 57 | which mandate particular programming practices |
| 58 | such as forbidding exceptions, multiple inheritance, |
| 59 | etc. However, as time goes on, we gradually add in more |
| 60 | information along this lines, either by copying |
| 61 | directly from Google's Style Guide or by writing |
| 62 | our own decisions and best practices, some of which |
| 63 | may be very WPILib-specific.</p> |
| 64 | |
| 65 | <p>As the original guide makes very clear, consistency |
| 66 | is extremely important to keeping the code base |
| 67 | manageable, and so we encourage that, wherever |
| 68 | reasonable, that you keep everything consistent |
| 69 | with whatever the standard style is.</p> |
| 70 | |
| 71 | <p>Along with just C++ style, it is also important |
| 72 | to keep in mind that WPILib consists of both a C++ |
| 73 | and Java half. In order to keep things consistent |
| 74 | and easier for users, we ask that, in general, |
| 75 | Java and C++ be kept as consistent with one another |
| 76 | as reasonable. This includes everything from using |
| 77 | two spaces for indentation in both language to |
| 78 | keeping the inheritance structure essentially the |
| 79 | same in both. Although the two do not have to be |
| 80 | precisely the same, it does mean that if there is |
| 81 | something that you are doing which will be imposssible |
| 82 | to reproduce in some way in Java, then you may |
| 83 | want to reconsider.</p> |
| 84 | |
| 85 | <p>One final thing to remember is that High School |
| 86 | students with relatively little experience programming |
| 87 | are the main user for this code, and throwing the full |
| 88 | brunt of C++ at a student just learning how to program |
| 89 | is likely not the best of ideas. As such, any |
| 90 | user-facing APIs should minimize the use of any |
| 91 | more complicated C++ features. As always, |
| 92 | use your judgement and ask others in cases where |
| 93 | there is something which may violate anything |
| 94 | in this guide.</p> |
| 95 | |
| 96 | <h2 id="Programming_Guidelines">Programming Guidelines</h2> |
| 97 | <p>C++ is a large, complicated language, and in order |
| 98 | to ensure that we stay consistent and maintain certain |
| 99 | best practices, we have certain rules. For the most part |
| 100 | these are common sense rules and in some cases exist |
| 101 | solely to point out features of C++ that someone more |
| 102 | familiar with Java may not realize even exist.</p> |
| 103 | |
| 104 | <h3 id="Pointers">Pointers</h3> |
| 105 | <p>In general, we strongly discourage the use of |
| 106 | raw pointers in C++ code; instead, references or |
| 107 | STL pointers should be used where appropriate. |
| 108 | There are two exceptions to this rule:</p> |
| 109 | <ul> |
| 110 | <li>When interfacing with lower-level C code or |
| 111 | with any libraries which force you to use raw pointers.</li> |
| 112 | <li>In order to keep user interfaces consistent, |
| 113 | we may keep around deprecated functions which |
| 114 | take raw pointers. Any user-facing functions |
| 115 | which take raw pointers should be deprecated |
| 116 | using the |
| 117 | <a href=https://en.wikipedia.org/wiki/C%2B%2B14#The_attribute_.5B.5Bdeprecated.5D.5D><code>[[deprecated]]</code></a> |
| 118 | attribute and replaced with either references |
| 119 | or STL pointers.</li> |
| 120 | </ul> |
| 121 | <p>As of C++11, the following are options in the |
| 122 | place of raw pointers:</p> |
| 123 | <ul> |
| 124 | <li><code>std::unique_ptr</code> Should be used |
| 125 | when you still need to use a pointer, but you |
| 126 | only need one entity to own the pointer. The |
| 127 | <code>std::unique_ptr</code> will automatically |
| 128 | be deleted when there are no more references to |
| 129 | it.</li> |
| 130 | <li><code>std::shared_ptr</code> Should be used |
| 131 | when you still need to use a pointer and you |
| 132 | need many references to the object. When |
| 133 | there are zero remaining references to the |
| 134 | object, it will be deleted. Use <code>std::weak_ptr</code> |
| 135 | where necessary to avoid circular dependencies |
| 136 | or other potential issues.</li> |
| 137 | <li>L-value references (the traditional sort |
| 138 | of reference that has been around since before C++11) |
| 139 | should be used when you want to pass around a |
| 140 | reference to an object and want to guarantee |
| 141 | that it won't be null. Use const references |
| 142 | if you want to avoid copying a large object |
| 143 | but don't want to modify it.</li> |
| 144 | <li>R-value references were introduced in C++11 |
| 145 | and allow for the use of <code>std::move</code>. |
| 146 | R-value references should be used where it makes |
| 147 | sense that a parameter to a function is having |
| 148 | its ownership passed from one place to another. |
| 149 | In general, R-value references are not inherently |
| 150 | bad, but they do introduce additional complexity |
| 151 | that may confuse people who are not familiar |
| 152 | with them.</li> |
| 153 | </ul> |
| 154 | |
| 155 | <h3 id="Deprecation">Deprecation</h3> |
| 156 | <p>When updating APIs, make liberal use of the |
| 157 | <code>[[deprecated]]</code> attribute (although if |
| 158 | it is reasonable to simply remove any old interfaces |
| 159 | then do so) to indicate that users should no longer |
| 160 | use the function. Currently, this will cause warnings |
| 161 | in user code and errors in the WPILib build.</p> |
| 162 | |
| 163 | <pre> |
| 164 | [[deprecated("This is a deprecated function; this text will be displayed when" |
| 165 | " the compiler throws a warning.")]] |
| 166 | void foo() {} |
| 167 | class [[deprecated("This is a deprecated class.")]] Foo {}; |
| 168 | int bar [[deprecated("This is a deprecated variable.")]]; |
| 169 | </pre> |
| 170 | |
| 171 | <p>See <a href=http://josephmansfield.uk/articles/marking-deprecated-c++14.html> |
| 172 | here</a> for more information on deprecation.</p> |
| 173 | |
| 174 | <h2 id="Header_Files">Header Files</h2> |
| 175 | |
| 176 | <p>In general, every <code>.cc</code> file should have an |
| 177 | associated <code>.h</code> file. There are some common |
| 178 | exceptions, such as unittests and |
| 179 | small <code>.cpp</code> files containing just a |
| 180 | <code>main()</code> function.</p> |
| 181 | |
| 182 | <p>Correct use of header files can make a huge difference to |
| 183 | the readability, size and performance of your code.</p> |
| 184 | |
| 185 | <p>The following rules will guide you through the various |
| 186 | pitfalls of using header files.</p> |
| 187 | |
| 188 | <a id="The_-inl.h_Files"></a> |
| 189 | <h3 id="Self_contained_Headers">Self-contained Headers</h3> |
| 190 | |
| 191 | <div class="summary"> |
| 192 | <p>Header files should be self-contained and end in <code>.h</code>. Files that |
| 193 | are meant for textual inclusion, but are not headers, should end in |
| 194 | <code>.inc</code>. Separate <code>-inl.h</code> headers are disallowed.</p> |
| 195 | </div> |
| 196 | |
| 197 | <div class="stylebody"> |
| 198 | <p>All header files should be self-contained. In other |
| 199 | words, users and refactoring tools should not have to adhere to special |
| 200 | conditions in order to include the header. Specifically, a |
| 201 | header should have <a href="#The__define_Guard">header guards</a>, |
| 202 | should include all other headers it needs, and should not require any |
| 203 | particular symbols to be defined.</p> |
| 204 | |
| 205 | <p>There are rare cases where a file is not meant to be self-contained, but |
| 206 | instead is meant to be textually included at a specific point in the code. |
| 207 | Examples are files that need to be included multiple times or |
| 208 | platform-specific extensions that essentially are part of other headers. Such |
| 209 | files should use the file extension <code>.inc</code>.</p> |
| 210 | |
| 211 | <p>If a template or inline function is declared in a <code>.h</code> file, |
| 212 | define it in that same file. The definitions of these constructs must |
| 213 | be included into every <code>.cc</code> file that uses them, or the |
| 214 | program may fail to link in some build configurations. Do not move these |
| 215 | definitions to separate <code>-inl.h</code> files.</p> |
| 216 | |
| 217 | <p>As an exception, a function template that is explicitly |
| 218 | instantiated for all relevant sets of template arguments, or |
| 219 | that is a private member of a class, may |
| 220 | be defined in the only <code>.cc</code> file that |
| 221 | instantiates the template.</p> |
| 222 | |
| 223 | </div> |
| 224 | |
| 225 | <h3 id="The__define_Guard">The #define Guard</h3> |
| 226 | |
| 227 | <div class="summary"> |
| 228 | <p>All header files should have <code>#define</code> guards to |
| 229 | prevent multiple inclusion. The format of the symbol name |
| 230 | should be |
| 231 | <code><i><PROJECT></i>_<i><PATH></i>_<i><FILE></i>_H_</code>.</p> |
| 232 | </div> |
| 233 | |
| 234 | <div class="stylebody"> |
| 235 | |
| 236 | |
| 237 | |
| 238 | <p>To guarantee uniqueness, they should |
| 239 | be based on the full path in a project's source tree. For |
| 240 | example, the file <code>foo/src/bar/baz.h</code> in |
| 241 | project <code>foo</code> should have the following |
| 242 | guard:</p> |
| 243 | |
| 244 | <pre>#ifndef FOO_BAR_BAZ_H_ |
| 245 | #define FOO_BAR_BAZ_H_ |
| 246 | |
| 247 | ... |
| 248 | |
| 249 | #endif // FOO_BAR_BAZ_H_ |
| 250 | </pre> |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | </div> |
| 256 | |
| 257 | <h3 id="Forward_Declarations">Forward Declarations</h3> |
| 258 | |
| 259 | <div class="summary"> |
| 260 | <p>You may forward declare ordinary classes in order to avoid |
| 261 | unnecessary <code>#include</code>s.</p> |
| 262 | </div> |
| 263 | |
| 264 | <div class="stylebody"> |
| 265 | |
| 266 | <div class="definition"> |
| 267 | <p>A "forward declaration" is a declaration of a class, |
| 268 | function, or template without an associated definition. |
| 269 | <code>#include</code> lines can often be replaced with |
| 270 | forward declarations of whatever symbols are actually |
| 271 | used by the client code.</p> |
| 272 | </div> |
| 273 | |
| 274 | <div class="pros"> |
| 275 | <ul> |
| 276 | <li>Unnecessary <code>#include</code>s force the |
| 277 | compiler to open more files and process more |
| 278 | input.</li> |
| 279 | |
| 280 | <li>They can also force your code to be recompiled more |
| 281 | often, due to changes in the header.</li> |
| 282 | </ul> |
| 283 | </div> |
| 284 | |
| 285 | <div class="cons"> |
| 286 | <ul> |
| 287 | <li>It can be difficult to determine the correct form |
| 288 | of a forward declaration in the presence of features |
| 289 | like templates, typedefs, default parameters, and using |
| 290 | declarations.</li> |
| 291 | |
| 292 | <li>It can be difficult to determine whether a forward |
| 293 | declaration or a full <code>#include</code> is needed |
| 294 | for a given piece of code, particularly when implicit |
| 295 | conversion operations are involved. In extreme cases, |
| 296 | replacing an <code>#include</code> with a forward |
| 297 | declaration can silently change the meaning of |
| 298 | code.</li> |
| 299 | |
| 300 | <li>Forward declaring multiple symbols from a header |
| 301 | can be more verbose than simply |
| 302 | <code>#include</code>ing the header.</li> |
| 303 | |
| 304 | <li>Forward declarations of functions and templates can |
| 305 | prevent the header owners from making |
| 306 | otherwise-compatible changes to their APIs; for |
| 307 | example, widening a parameter type, or adding a |
| 308 | template parameter with a default value.</li> |
| 309 | <li>Forward declaring symbols from namespace |
| 310 | <code>std::</code> usually yields undefined |
| 311 | behavior.</li> |
| 312 | |
| 313 | <li>Structuring code to enable forward declarations |
| 314 | (e.g. using pointer members instead of object members) |
| 315 | can make the code slower and more complex.</li> |
| 316 | |
| 317 | <li>The practical efficiency benefits of forward |
| 318 | declarations are unproven.</li> |
| 319 | </ul> |
| 320 | </div> |
| 321 | |
| 322 | <div class="decision"> |
| 323 | <ul> |
| 324 | <li>When using a function declared in a header file, |
| 325 | always <code>#include</code> that header.</li> |
| 326 | |
| 327 | <li>When using a class template, prefer to |
| 328 | <code>#include</code> its header file.</li> |
| 329 | |
| 330 | <li>When using an ordinary class, relying on a forward |
| 331 | declaration is OK, but be wary of situations where a |
| 332 | forward declaration may be insufficient or incorrect; |
| 333 | when in doubt, just <code>#include</code> the |
| 334 | appropriate header.</li> |
| 335 | |
| 336 | <li>Do not replace data members with pointers just to |
| 337 | avoid an <code>#include</code>.</li> |
| 338 | </ul> |
| 339 | |
| 340 | <p>Please see <a href="#Names_and_Order_of_Includes">Names and Order |
| 341 | of Includes</a> for rules about when to #include a header.</p> |
| 342 | </div> |
| 343 | |
| 344 | </div> |
| 345 | |
| 346 | <h3 id="Inline_Functions">Inline Functions</h3> |
| 347 | |
| 348 | <div class="summary"> |
| 349 | <p>Define functions inline only when they are small, say, 10 |
| 350 | lines or less.</p> |
| 351 | </div> |
| 352 | |
| 353 | <div class="stylebody"> |
| 354 | |
| 355 | <div class="definition"> |
| 356 | <p>You can declare functions in a way that allows the compiler to expand |
| 357 | them inline rather than calling them through the usual |
| 358 | function call mechanism.</p> |
| 359 | </div> |
| 360 | |
| 361 | <div class="pros"> |
| 362 | <p>Inlining a function can generate more efficient object |
| 363 | code, as long as the inlined function is small. Feel free |
| 364 | to inline accessors and mutators, and other short, |
| 365 | performance-critical functions.</p> |
| 366 | </div> |
| 367 | |
| 368 | <div class="cons"> |
| 369 | <p>Overuse of inlining can actually make programs slower. |
| 370 | Depending on a function's size, inlining it can cause the |
| 371 | code size to increase or decrease. Inlining a very small |
| 372 | accessor function will usually decrease code size while |
| 373 | inlining a very large function can dramatically increase |
| 374 | code size. On modern processors smaller code usually runs |
| 375 | faster due to better use of the instruction cache.</p> |
| 376 | </div> |
| 377 | |
| 378 | <div class="decision"> |
| 379 | <p>A decent rule of thumb is to not inline a function if |
| 380 | it is more than 10 lines long. Beware of destructors, |
| 381 | which are often longer than they appear because of |
| 382 | implicit member- and base-destructor calls!</p> |
| 383 | |
| 384 | <p>Another useful rule of thumb: it's typically not cost |
| 385 | effective to inline functions with loops or switch |
| 386 | statements (unless, in the common case, the loop or |
| 387 | switch statement is never executed).</p> |
| 388 | |
| 389 | <p>It is important to know that functions are not always |
| 390 | inlined even if they are declared as such; for example, |
| 391 | virtual and recursive functions are not normally inlined. |
| 392 | Usually recursive functions should not be inline. The |
| 393 | main reason for making a virtual function inline is to |
| 394 | place its definition in the class, either for convenience |
| 395 | or to document its behavior, e.g., for accessors and |
| 396 | mutators.</p> |
| 397 | </div> |
| 398 | |
| 399 | </div> |
| 400 | |
| 401 | <h3 id="Function_Parameter_Ordering">Function Parameter Ordering</h3> |
| 402 | |
| 403 | <div class="summary"> |
| 404 | <p>When defining a function, parameter order is: inputs, then |
| 405 | outputs.</p> |
| 406 | </div> |
| 407 | |
| 408 | <div class="stylebody"> |
| 409 | <p>Parameters to C/C++ functions are either input to the |
| 410 | function, output from the function, or both. Input |
| 411 | parameters are usually values or <code>const</code> |
| 412 | references, while output and input/output parameters will |
| 413 | be non-<code>const</code> pointers. When ordering |
| 414 | function parameters, put all input-only parameters before |
| 415 | any output parameters. In particular, do not add new |
| 416 | parameters to the end of the function just because they |
| 417 | are new; place new input-only parameters before the |
| 418 | output parameters.</p> |
| 419 | |
| 420 | <p>This is not a hard-and-fast rule. Parameters that are |
| 421 | both input and output (often classes/structs) muddy the |
| 422 | waters, and, as always, consistency with related |
| 423 | functions may require you to bend the rule.</p> |
| 424 | |
| 425 | </div> |
| 426 | |
| 427 | <h3 id="Names_and_Order_of_Includes">Names and Order of Includes</h3> |
| 428 | |
| 429 | <div class="summary"> |
| 430 | <p>Use standard order for readability and to avoid hidden |
| 431 | dependencies: Related header, C library, C++ library, other libraries' |
| 432 | <code>.h</code>, your project's <code>.h</code>.</p> |
| 433 | </div> |
| 434 | |
| 435 | <div class="stylebody"> |
| 436 | <p> |
| 437 | All of a project's header files should be |
| 438 | listed as descendants of the project's source |
| 439 | directory without use of UNIX directory shortcuts |
| 440 | <code>.</code> (the current directory) or <code>..</code> |
| 441 | (the parent directory). For example, |
| 442 | |
| 443 | <code>google-awesome-project/src/base/logging.h</code> |
| 444 | should be included as:</p> |
| 445 | |
| 446 | <pre>#include "base/logging.h" |
| 447 | </pre> |
| 448 | |
| 449 | <p>In <code><var>dir/foo</var>.cc</code> or |
| 450 | <code><var>dir/foo_test</var>.cc</code>, whose main |
| 451 | purpose is to implement or test the stuff in |
| 452 | <code><var>dir2/foo2</var>.h</code>, order your includes |
| 453 | as follows:</p> |
| 454 | |
| 455 | <ol> |
| 456 | <li><code><var>dir2/foo2</var>.h</code>.</li> |
| 457 | |
| 458 | <li>C system files.</li> |
| 459 | |
| 460 | <li>C++ system files.</li> |
| 461 | |
| 462 | <li>Other libraries' <code>.h</code> |
| 463 | files.</li> |
| 464 | |
| 465 | <li> |
| 466 | Your project's <code>.h</code> |
| 467 | files.</li> |
| 468 | </ol> |
| 469 | |
| 470 | <p>With the preferred ordering, if |
| 471 | <code><var>dir2/foo2</var>.h</code> omits any necessary |
| 472 | includes, the build of <code><var>dir/foo</var>.cc</code> |
| 473 | or <code><var>dir/foo</var>_test.cc</code> will break. |
| 474 | Thus, this rule ensures that build breaks show up first |
| 475 | for the people working on these files, not for innocent |
| 476 | people in other packages.</p> |
| 477 | |
| 478 | <p><code><var>dir/foo</var>.cc</code> and |
| 479 | <code><var>dir2/foo2</var>.h</code> are usually in the same |
| 480 | directory (e.g. <code>base/basictypes_test.cc</code> and |
| 481 | <code>base/basictypes.h</code>), but may sometimes be in different |
| 482 | directories too.</p> |
| 483 | |
| 484 | |
| 485 | |
| 486 | <p>Within each section the includes should be ordered |
| 487 | alphabetically. Note that older code might not conform to |
| 488 | this rule and should be fixed when convenient.</p> |
| 489 | |
| 490 | <p>You should include all the headers that define the symbols you rely |
| 491 | upon (except in cases of <a href="#Forward_Declarations">forward |
| 492 | declaration</a>). If you rely on symbols from <code>bar.h</code>, |
| 493 | don't count on the fact that you included <code>foo.h</code> which |
| 494 | (currently) includes <code>bar.h</code>: include <code>bar.h</code> |
| 495 | yourself, unless <code>foo.h</code> explicitly demonstrates its intent |
| 496 | to provide you the symbols of <code>bar.h</code>. However, any |
| 497 | includes present in the related header do not need to be included |
| 498 | again in the related <code>cc</code> (i.e., <code>foo.cc</code> can |
| 499 | rely on <code>foo.h</code>'s includes).</p> |
| 500 | |
| 501 | <p>For example, the includes in |
| 502 | |
| 503 | <code>google-awesome-project/src/foo/internal/fooserver.cc</code> |
| 504 | might look like this:</p> |
| 505 | |
| 506 | |
| 507 | <pre>#include "foo/server/fooserver.h" |
| 508 | |
| 509 | #include <sys/types.h> |
| 510 | #include <unistd.h> |
| 511 | #include <hash_map> |
| 512 | #include <vector> |
| 513 | |
| 514 | #include "base/basictypes.h" |
| 515 | #include "base/commandlineflags.h" |
| 516 | #include "foo/server/bar.h" |
| 517 | </pre> |
| 518 | |
| 519 | <p class="exception">Sometimes, system-specific code needs |
| 520 | conditional includes. Such code can put conditional |
| 521 | includes after other includes. Of course, keep your |
| 522 | system-specific code small and localized. Example:</p> |
| 523 | |
| 524 | <pre>#include "foo/public/fooserver.h" |
| 525 | |
| 526 | #include "base/port.h" // For LANG_CXX11. |
| 527 | |
| 528 | #ifdef LANG_CXX11 |
| 529 | #include <initializer_list> |
| 530 | #endif // LANG_CXX11 |
| 531 | </pre> |
| 532 | |
| 533 | </div> |
| 534 | |
| 535 | <h2 id="Naming">Naming</h2> |
| 536 | |
| 537 | <p>The most important consistency rules are those that govern |
| 538 | naming. The style of a name immediately informs us what sort of |
| 539 | thing the named entity is: a type, a variable, a function, a |
| 540 | constant, a macro, etc., without requiring us to search for the |
| 541 | declaration of that entity. The pattern-matching engine in our |
| 542 | brains relies a great deal on these naming rules. |
| 543 | </p> |
| 544 | |
| 545 | <p>Naming rules are pretty arbitrary, but |
| 546 | we feel that |
| 547 | consistency is more important than individual preferences in this |
| 548 | area, so regardless of whether you find them sensible or not, |
| 549 | the rules are the rules.</p> |
| 550 | |
| 551 | <h3 id="General_Naming_Rules">General Naming Rules</h3> |
| 552 | |
| 553 | <div class="summary"> |
| 554 | <p>Function names, variable names, and filenames should be |
| 555 | descriptive; eschew abbreviation.</p> |
| 556 | </div> |
| 557 | |
| 558 | <div class="stylebody"> |
| 559 | <p>Give as descriptive a name as possible, within reason. |
| 560 | Do not worry about saving horizontal space as it is far |
| 561 | more important to make your code immediately |
| 562 | understandable by a new reader. Do not use abbreviations |
| 563 | that are ambiguous or unfamiliar to readers outside your |
| 564 | project, and do not abbreviate by deleting letters within |
| 565 | a word.</p> |
| 566 | |
| 567 | <pre>int price_count_reader; // No abbreviation. |
| 568 | int num_errors; // "num" is a widespread convention. |
| 569 | int num_dns_connections; // Most people know what "DNS" stands for. |
| 570 | </pre> |
| 571 | |
| 572 | <pre class="badcode">int n; // Meaningless. |
| 573 | int nerr; // Ambiguous abbreviation. |
| 574 | int n_comp_conns; // Ambiguous abbreviation. |
| 575 | int wgc_connections; // Only your group knows what this stands for. |
| 576 | int pc_reader; // Lots of things can be abbreviated "pc". |
| 577 | int cstmr_id; // Deletes internal letters. |
| 578 | </pre> |
| 579 | |
| 580 | </div> |
| 581 | |
| 582 | <h3 id="File_Names">File Names</h3> |
| 583 | |
| 584 | <div class="summary"> |
| 585 | <p>Filenames should be all lowercase and can include |
| 586 | underscores (<code>_</code>) or dashes (<code>-</code>). |
| 587 | Follow the convention that your |
| 588 | |
| 589 | project uses. If there is no consistent |
| 590 | local pattern to follow, prefer "_".</p> |
| 591 | </div> |
| 592 | |
| 593 | <div class="stylebody"> |
| 594 | |
| 595 | <p>Examples of acceptable file names:</p> |
| 596 | |
| 597 | <ul> |
| 598 | <li><code>my_useful_class.cc</code></li> |
| 599 | <li><code>my-useful-class.cc</code></li> |
| 600 | <li><code>myusefulclass.cc</code></li> |
| 601 | <li><code>myusefulclass_test.cc // _unittest and _regtest are deprecated.</code></li> |
| 602 | </ul> |
| 603 | |
| 604 | <p>C++ files should end in <code>.cc</code> and header files should end in |
| 605 | <code>.h</code>. Files that rely on being textually included at specific points |
| 606 | should end in <code>.inc</code> (see also the section on |
| 607 | <a href="#Self_contained_Headers">self-contained headers</a>).</p> |
| 608 | |
| 609 | <p>Do not use filenames that already exist in |
| 610 | <code>/usr/include</code>, such as <code>db.h</code>.</p> |
| 611 | |
| 612 | <p>In general, make your filenames very specific. For |
| 613 | example, use <code>http_server_logs.h</code> rather than |
| 614 | <code>logs.h</code>. A very common case is to have a pair |
| 615 | of files called, e.g., <code>foo_bar.h</code> and |
| 616 | <code>foo_bar.cc</code>, defining a class called |
| 617 | <code>FooBar</code>.</p> |
| 618 | |
| 619 | <p>Inline functions must be in a <code>.h</code> file. If |
| 620 | your inline functions are very short, they should go |
| 621 | directly into your <code>.h</code> file. </p> |
| 622 | |
| 623 | </div> |
| 624 | |
| 625 | <h3 id="Type_Names">Type Names</h3> |
| 626 | |
| 627 | <div class="summary"> |
| 628 | <p>Type names start with a capital letter and have a capital |
| 629 | letter for each new word, with no underscores: |
| 630 | <code>MyExcitingClass</code>, <code>MyExcitingEnum</code>.</p> |
| 631 | </div> |
| 632 | |
| 633 | <div class="stylebody"> |
| 634 | |
| 635 | <p>The names of all types — classes, structs, typedefs, |
| 636 | and enums — have the same naming convention. Type names |
| 637 | should start with a capital letter and have a capital letter |
| 638 | for each new word. No underscores. For example:</p> |
| 639 | |
| 640 | <pre>// classes and structs |
| 641 | class UrlTable { ... |
| 642 | class UrlTableTester { ... |
| 643 | struct UrlTableProperties { ... |
| 644 | |
| 645 | // typedefs |
| 646 | typedef hash_map<UrlTableProperties *, string> PropertiesMap; |
| 647 | |
| 648 | // enums |
| 649 | enum UrlTableErrors { ... |
| 650 | </pre> |
| 651 | |
| 652 | </div> |
| 653 | |
| 654 | <h3 id="Variable_Names">Variable Names</h3> |
| 655 | |
| 656 | <div class="summary"> |
| 657 | <p>The names of variables and data members are all lowercase, with |
| 658 | underscores between words. Data members of classes (but not structs) |
| 659 | additionally are prefixed with "m_". For instance: |
| 660 | <code>a_local_variable</code>, <code>a_struct_data_member</code>, |
| 661 | <code>m_a_class_data_member</code>.</p> |
| 662 | </div> |
| 663 | |
| 664 | <div class="stylebody"> |
| 665 | |
| 666 | <h4 class="stylepoint_subsection">Common Variable names</h4> |
| 667 | |
| 668 | <p>For example:</p> |
| 669 | |
| 670 | <pre>string table_name; // OK - uses underscore. |
| 671 | string tablename; // OK - all lowercase. |
| 672 | </pre> |
| 673 | |
| 674 | <pre class="badcode">string tableName; // Bad - mixed case. |
| 675 | </pre> |
| 676 | |
| 677 | <h4 class="stylepoint_subsection">Class Data Members</h4> |
| 678 | |
| 679 | <p>Data members of classes, both static and non-static, are |
| 680 | named like ordinary nonmember variables, but prefixed with a |
| 681 | "m_".</p> |
| 682 | |
| 683 | <pre>class TableInfo { |
| 684 | ... |
| 685 | private: |
| 686 | string m_table_name; // OK - m_ at beginning. |
| 687 | string m_tablename; // OK. |
| 688 | static Pool<TableInfo>* m_pool; // OK. |
| 689 | }; |
| 690 | </pre> |
| 691 | |
| 692 | <h4 class="stylepoint_subsection">Struct Data Members</h4> |
| 693 | |
| 694 | <p>Data members of structs, both static and non-static, |
| 695 | are named like ordinary nonmember variables. They do not have |
| 696 | the preceding "m_" that data members in classes have.</p> |
| 697 | |
| 698 | <pre>struct UrlTableProperties { |
| 699 | string name; |
| 700 | int num_entries; |
| 701 | static Pool<UrlTableProperties>* pool; |
| 702 | }; |
| 703 | </pre> |
| 704 | |
| 705 | |
| 706 | <p>See <a href="#Structs_vs._Classes">Structs vs. |
| 707 | Classes</a> for a discussion of when to use a struct |
| 708 | versus a class.</p> |
| 709 | |
| 710 | <h4 class="stylepoint_subsection">Global Variables</h4> |
| 711 | |
| 712 | <p>There are no special requirements for global |
| 713 | variables, which should be rare in any case, but if you |
| 714 | use one, consider prefixing it with <code>g_</code> or |
| 715 | some other marker to easily distinguish it from local |
| 716 | variables.</p> |
| 717 | |
| 718 | </div> |
| 719 | |
| 720 | <h3 id="Constant_Names">Constant Names</h3> |
| 721 | |
| 722 | <div class="summary"> |
| 723 | <p>Use a <code>k</code> followed by mixed case, e.g., |
| 724 | <code>kDaysInAWeek</code>, for constants defined globally or within a class.</p> |
| 725 | </div> |
| 726 | |
| 727 | <div class="stylebody"> |
| 728 | |
| 729 | <p>As a convenience to the reader, compile-time constants of global or class scope |
| 730 | follow a different naming convention from other variables. |
| 731 | Use a <code>k</code> followed by words with uppercase first letters:</p> |
| 732 | |
| 733 | <pre>const int kDaysInAWeek = 7; |
| 734 | </pre> |
| 735 | |
| 736 | <p>This convention may optionally be used for compile-time constants of local scope; |
| 737 | otherwise the usual variable naming rules apply. |
| 738 | |
| 739 | </p></div> |
| 740 | |
| 741 | <h3 id="Function_Names">Function Names</h3> |
| 742 | |
| 743 | <div class="summary"> |
| 744 | <p>Regular functions have mixed case; accessors and mutators |
| 745 | match the name of the variable: |
| 746 | <code>MyExcitingFunction()</code>, |
| 747 | <code>MyExcitingMethod()</code>, |
| 748 | <code>my_exciting_member_variable()</code>, |
| 749 | <code>set_my_exciting_member_variable()</code>.</p> |
| 750 | </div> |
| 751 | |
| 752 | <div class="stylebody"> |
| 753 | |
| 754 | <h4 class="stylepoint_subsection">Regular Functions</h4> |
| 755 | |
| 756 | <p>Functions should start with a capital letter and have |
| 757 | a capital letter for each new word. No underscores.</p> |
| 758 | |
| 759 | <p>If your function crashes upon an error, you should |
| 760 | append OrDie to the function name. This only applies to |
| 761 | functions which could be used by production code and to |
| 762 | errors that are reasonably likely to occur during normal |
| 763 | operation.</p> |
| 764 | |
| 765 | <pre>AddTableEntry() |
| 766 | DeleteUrl() |
| 767 | OpenFileOrDie() |
| 768 | </pre> |
| 769 | |
| 770 | <h4 class="stylepoint_subsection">Accessors and Mutators</h4> |
| 771 | |
| 772 | <p>Accessors and mutators (get and set functions) should |
| 773 | match the name of the variable they are getting and |
| 774 | setting. This shows an excerpt of a class whose instance |
| 775 | variable is <code>num_entries_</code>.</p> |
| 776 | |
| 777 | <pre>class MyClass { |
| 778 | public: |
| 779 | ... |
| 780 | int num_entries() const { return num_entries_; } |
| 781 | void set_num_entries(int num_entries) { num_entries_ = num_entries; } |
| 782 | |
| 783 | private: |
| 784 | int num_entries_; |
| 785 | }; |
| 786 | </pre> |
| 787 | |
| 788 | <p>You may also use lowercase letters for other very |
| 789 | short inlined functions. For example if a function were |
| 790 | so cheap you would not cache the value if you were |
| 791 | calling it in a loop, then lowercase naming would be |
| 792 | acceptable.</p> |
| 793 | |
| 794 | </div> |
| 795 | |
| 796 | <h3 id="Namespace_Names">Namespace Names</h3> |
| 797 | |
| 798 | <div class="summary"> |
| 799 | |
| 800 | |
| 801 | <p>Namespace names are all lower-case, |
| 802 | and based on project names and possibly their directory |
| 803 | structure: <code>google_awesome_project</code>.</p> |
| 804 | </div> |
| 805 | |
| 806 | <div class="stylebody"> |
| 807 | |
| 808 | <p>See <a href="#Namespaces">Namespaces</a> for a |
| 809 | discussion of namespaces and how to name them.</p> |
| 810 | |
| 811 | </div> |
| 812 | |
| 813 | <h3 id="Enumerator_Names">Enumerator Names</h3> |
| 814 | |
| 815 | <div class="summary"> |
| 816 | <p>Enumerators should be named <i>either</i> like |
| 817 | <a href="#Constant_Names">constants</a> or like |
| 818 | <a href="#Macro_Names">macros</a>: either <code>kEnumName</code> or |
| 819 | <code>ENUM_NAME</code>.</p> |
| 820 | </div> |
| 821 | |
| 822 | <div class="stylebody"> |
| 823 | |
| 824 | <p>Preferably, the individual enumerators should be named |
| 825 | like <a href="#Constant_Names">constants</a>. However, it |
| 826 | is also acceptable to name them like |
| 827 | <a href="Macro_Names">macros</a>. The enumeration name, |
| 828 | <code>UrlTableErrors</code> (and |
| 829 | <code>AlternateUrlTableErrors</code>), is a type, and |
| 830 | therefore mixed case.</p> |
| 831 | |
| 832 | <pre>enum UrlTableErrors { |
| 833 | kOK = 0, |
| 834 | kErrorOutOfMemory, |
| 835 | kErrorMalformedInput, |
| 836 | }; |
| 837 | enum AlternateUrlTableErrors { |
| 838 | OK = 0, |
| 839 | OUT_OF_MEMORY = 1, |
| 840 | MALFORMED_INPUT = 2, |
| 841 | }; |
| 842 | </pre> |
| 843 | |
| 844 | <p>Until January 2009, the style was to name enum values |
| 845 | like <a href="#Macro_Names">macros</a>. This caused |
| 846 | problems with name collisions between enum values and |
| 847 | macros. Hence, the change to prefer constant-style naming |
| 848 | was put in place. New code should prefer constant-style |
| 849 | naming if possible. However, there is no reason to change |
| 850 | old code to use constant-style names, unless the old |
| 851 | names are actually causing a compile-time problem.</p> |
| 852 | |
| 853 | |
| 854 | |
| 855 | </div> |
| 856 | |
| 857 | <h3 id="Macro_Names">Macro Names</h3> |
| 858 | |
| 859 | <div class="summary"> |
| 860 | <p>You're not really going to <a href="#Preprocessor_Macros"> |
| 861 | define a macro</a>, are you? If you do, they're like this: |
| 862 | <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN</code>.</p> |
| 863 | </div> |
| 864 | |
| 865 | <div class="stylebody"> |
| 866 | |
| 867 | <p>Please see the <a href="#Preprocessor_Macros">description |
| 868 | of macros</a>; in general macros should <em>not</em> be used. |
| 869 | However, if they are absolutely needed, then they should be |
| 870 | named with all capitals and underscores.</p> |
| 871 | |
| 872 | <pre>#define ROUND(x) ... |
| 873 | #define PI_ROUNDED 3.0 |
| 874 | </pre> |
| 875 | |
| 876 | </div> |
| 877 | |
| 878 | <h3 id="Exceptions_to_Naming_Rules">Exceptions to Naming Rules</h3> |
| 879 | |
| 880 | <div class="summary"> |
| 881 | <p>If you are naming something that is analogous to an |
| 882 | existing C or C++ entity then you can follow the existing |
| 883 | naming convention scheme.</p> |
| 884 | </div> |
| 885 | |
| 886 | <div class="stylebody"> |
| 887 | |
| 888 | <dl> |
| 889 | <dt><code>bigopen()</code></dt> |
| 890 | <dd>function name, follows form of <code>open()</code></dd> |
| 891 | |
| 892 | <dt><code>uint</code></dt> |
| 893 | <dd><code>typedef</code></dd> |
| 894 | |
| 895 | <dt><code>bigpos</code></dt> |
| 896 | <dd><code>struct</code> or <code>class</code>, follows |
| 897 | form of <code>pos</code></dd> |
| 898 | |
| 899 | <dt><code>sparse_hash_map</code></dt> |
| 900 | <dd>STL-like entity; follows STL naming conventions</dd> |
| 901 | |
| 902 | <dt><code>LONGLONG_MAX</code></dt> |
| 903 | <dd>a constant, as in <code>INT_MAX</code></dd> |
| 904 | </dl> |
| 905 | |
| 906 | </div> |
| 907 | |
| 908 | <h2 id="Comments">Comments</h2> |
| 909 | |
| 910 | <p>Though a pain to write, comments are absolutely vital to |
| 911 | keeping our code readable. The following rules describe what |
| 912 | you should comment and where. But remember: while comments are |
| 913 | very important, the best code is self-documenting. Giving |
| 914 | sensible names to types and variables is much better than using |
| 915 | obscure names that you must then explain through comments.</p> |
| 916 | |
| 917 | <p>When writing your comments, write for your audience: the |
| 918 | next |
| 919 | contributor who will need to |
| 920 | understand your code. Be generous — the next |
| 921 | one may be you!</p> |
| 922 | |
| 923 | <h3 id="Comment_Style">Comment Style</h3> |
| 924 | |
| 925 | <div class="summary"> |
| 926 | <p>Use either the <code>//</code> or <code>/* */</code> |
| 927 | syntax, as long as you are consistent.</p> |
| 928 | </div> |
| 929 | |
| 930 | <div class="stylebody"> |
| 931 | |
| 932 | <p>You can use either the <code>//</code> or the <code>/* |
| 933 | */</code> syntax; however, <code>//</code> is |
| 934 | <em>much</em> more common. Be consistent with how you |
| 935 | comment and what style you use where.</p> |
| 936 | |
| 937 | </div> |
| 938 | |
| 939 | <h3 id="File_Comments">File Comments</h3> |
| 940 | |
| 941 | <div class="summary"> |
| 942 | <p> Start each file with license |
| 943 | boilerplate, followed by a description of its |
| 944 | contents.</p> |
| 945 | </div> |
| 946 | |
| 947 | <div class="stylebody"> |
| 948 | |
| 949 | <h4 class="stylepoint_subsection">Legal Notice and Author |
| 950 | Line</h4> |
| 951 | |
| 952 | |
| 953 | |
| 954 | <p>Every file should contain license |
| 955 | boilerplate. Choose the appropriate boilerplate for the |
| 956 | license used by the project (for example, Apache 2.0, |
| 957 | BSD, LGPL, GPL).</p> |
| 958 | |
| 959 | <p>If you make significant changes to a file with an |
| 960 | author line, consider deleting the author line.</p> |
| 961 | |
| 962 | <h4 class="stylepoint_subsection">File Contents</h4> |
| 963 | |
| 964 | <p>Every file should have a comment at the top describing |
| 965 | its contents.</p> |
| 966 | |
| 967 | <p>Generally a <code>.h</code> file will describe the |
| 968 | classes that are declared in the file with an overview of |
| 969 | what they are for and how they are used. A |
| 970 | <code>.cc</code> file should contain more information |
| 971 | about implementation details or discussions of tricky |
| 972 | algorithms. If you feel the implementation details or a |
| 973 | discussion of the algorithms would be useful for someone |
| 974 | reading the <code>.h</code>, feel free to put it there |
| 975 | instead, but mention in the <code>.cc</code> that the |
| 976 | documentation is in the <code>.h</code> file.</p> |
| 977 | |
| 978 | <p>Do not duplicate comments in both the <code>.h</code> |
| 979 | and the <code>.cc</code>. Duplicated comments |
| 980 | diverge.</p> |
| 981 | |
| 982 | </div> |
| 983 | |
| 984 | <h3 id="Class_Comments">Class Comments</h3> |
| 985 | |
| 986 | <div class="summary"> |
| 987 | <p>Every class definition should have an accompanying comment |
| 988 | that describes what it is for and how it should be used.</p> |
| 989 | </div> |
| 990 | |
| 991 | <div class="stylebody"> |
| 992 | |
| 993 | <pre>// Iterates over the contents of a GargantuanTable. Sample usage: |
| 994 | // GargantuanTableIterator* iter = table->NewIterator(); |
| 995 | // for (iter->Seek("foo"); !iter->done(); iter->Next()) { |
| 996 | // process(iter->key(), iter->value()); |
| 997 | // } |
| 998 | // delete iter; |
| 999 | class GargantuanTableIterator { |
| 1000 | ... |
| 1001 | }; |
| 1002 | </pre> |
| 1003 | |
| 1004 | <p>If you have already described a class in detail in the |
| 1005 | comments at the top of your file feel free to simply |
| 1006 | state "See comment at top of file for a complete |
| 1007 | description", but be sure to have some sort of |
| 1008 | comment.</p> |
| 1009 | |
| 1010 | <p>Document the synchronization assumptions the class |
| 1011 | makes, if any. If an instance of the class can be |
| 1012 | accessed by multiple threads, take extra care to document |
| 1013 | the rules and invariants surrounding multithreaded |
| 1014 | use.</p> |
| 1015 | |
| 1016 | </div> |
| 1017 | |
| 1018 | <h3 id="Function_Comments">Function Comments</h3> |
| 1019 | |
| 1020 | <div class="summary"> |
| 1021 | <p>Declaration comments describe use of the function; comments |
| 1022 | at the definition of a function describe operation.</p> |
| 1023 | </div> |
| 1024 | |
| 1025 | <div class="stylebody"> |
| 1026 | |
| 1027 | <h4 class="stylepoint_subsection">Function Declarations</h4> |
| 1028 | |
| 1029 | <p>Every function declaration should have comments |
| 1030 | immediately preceding it that describe what the function |
| 1031 | does and how to use it. These comments should be |
| 1032 | descriptive ("Opens the file") rather than imperative |
| 1033 | ("Open the file"); the comment describes the function, it |
| 1034 | does not tell the function what to do. In general, these |
| 1035 | comments do not describe how the function performs its |
| 1036 | task. Instead, that should be left to comments in the |
| 1037 | function definition.</p> |
| 1038 | |
| 1039 | <p>Types of things to mention in comments at the function |
| 1040 | declaration:</p> |
| 1041 | |
| 1042 | <ul> |
| 1043 | <li>What the inputs and outputs are.</li> |
| 1044 | |
| 1045 | <li>For class member functions: whether the object |
| 1046 | remembers reference arguments beyond the duration of |
| 1047 | the method call, and whether it will free them or |
| 1048 | not.</li> |
| 1049 | |
| 1050 | <li>If the function allocates memory that the caller |
| 1051 | must free.</li> |
| 1052 | |
| 1053 | <li>Whether any of the arguments can be a null |
| 1054 | pointer.</li> |
| 1055 | |
| 1056 | <li>If there are any performance implications of how a |
| 1057 | function is used.</li> |
| 1058 | |
| 1059 | <li>If the function is re-entrant. What are its |
| 1060 | synchronization assumptions?</li> |
| 1061 | </ul> |
| 1062 | |
| 1063 | <p>Here is an example:</p> |
| 1064 | |
| 1065 | <pre>// Returns an iterator for this table. It is the client's |
| 1066 | // responsibility to delete the iterator when it is done with it, |
| 1067 | // and it must not use the iterator once the GargantuanTable object |
| 1068 | // on which the iterator was created has been deleted. |
| 1069 | // |
| 1070 | // The iterator is initially positioned at the beginning of the table. |
| 1071 | // |
| 1072 | // This method is equivalent to: |
| 1073 | // Iterator* iter = table->NewIterator(); |
| 1074 | // iter->Seek(""); |
| 1075 | // return iter; |
| 1076 | // If you are going to immediately seek to another place in the |
| 1077 | // returned iterator, it will be faster to use NewIterator() |
| 1078 | // and avoid the extra seek. |
| 1079 | Iterator* GetIterator() const; |
| 1080 | </pre> |
| 1081 | |
| 1082 | <p>However, do not be unnecessarily verbose or state the |
| 1083 | completely obvious. Notice below that it is not necessary |
| 1084 | to say "returns false otherwise" because this is |
| 1085 | implied.</p> |
| 1086 | |
| 1087 | <pre>// Returns true if the table cannot hold any more entries. |
| 1088 | bool IsTableFull(); |
| 1089 | </pre> |
| 1090 | |
| 1091 | <p>When commenting constructors and destructors, remember |
| 1092 | that the person reading your code knows what constructors |
| 1093 | and destructors are for, so comments that just say |
| 1094 | something like "destroys this object" are not useful. |
| 1095 | Document what constructors do with their arguments (for |
| 1096 | example, if they take ownership of pointers), and what |
| 1097 | cleanup the destructor does. If this is trivial, just |
| 1098 | skip the comment. It is quite common for destructors not |
| 1099 | to have a header comment.</p> |
| 1100 | |
| 1101 | <h4 class="stylepoint_subsection">Function Definitions</h4> |
| 1102 | |
| 1103 | <p>If there is anything tricky about how a function does |
| 1104 | its job, the function definition should have an |
| 1105 | explanatory comment. For example, in the definition |
| 1106 | comment you might describe any coding tricks you use, |
| 1107 | give an overview of the steps you go through, or explain |
| 1108 | why you chose to implement the function in the way you |
| 1109 | did rather than using a viable alternative. For instance, |
| 1110 | you might mention why it must acquire a lock for the |
| 1111 | first half of the function but why it is not needed for |
| 1112 | the second half.</p> |
| 1113 | |
| 1114 | <p>Note you should <em>not</em> just repeat the comments |
| 1115 | given with the function declaration, in the |
| 1116 | <code>.h</code> file or wherever. It's okay to |
| 1117 | recapitulate briefly what the function does, but the |
| 1118 | focus of the comments should be on how it does it.</p> |
| 1119 | |
| 1120 | </div> |
| 1121 | |
| 1122 | <h3 id="Variable_Comments">Variable Comments</h3> |
| 1123 | |
| 1124 | <div class="summary"> |
| 1125 | <p>In general the actual name of the variable should be |
| 1126 | descriptive enough to give a good idea of what the variable |
| 1127 | is used for. In certain cases, more comments are required.</p> |
| 1128 | </div> |
| 1129 | |
| 1130 | <div class="stylebody"> |
| 1131 | |
| 1132 | <h4 class="stylepoint_subsection">Class Data Members</h4> |
| 1133 | |
| 1134 | <p>Each class data member (also called an instance |
| 1135 | variable or member variable) should have a comment |
| 1136 | describing what it is used for. If the variable can take |
| 1137 | sentinel values with special meanings, such as a null |
| 1138 | pointer or -1, document this. For example:</p> |
| 1139 | |
| 1140 | |
| 1141 | <pre>private: |
| 1142 | // Keeps track of the total number of entries in the table. |
| 1143 | // Used to ensure we do not go over the limit. -1 means |
| 1144 | // that we don't yet know how many entries the table has. |
| 1145 | int num_total_entries_; |
| 1146 | </pre> |
| 1147 | |
| 1148 | <h4 class="stylepoint_subsection">Global Variables</h4> |
| 1149 | |
| 1150 | <p>As with data members, all global variables should have |
| 1151 | a comment describing what they are and what they are used |
| 1152 | for. For example:</p> |
| 1153 | |
| 1154 | <pre>// The total number of tests cases that we run through in this regression test. |
| 1155 | const int kNumTestCases = 6; |
| 1156 | </pre> |
| 1157 | |
| 1158 | </div> |
| 1159 | |
| 1160 | <h3 id="Implementation_Comments">Implementation Comments</h3> |
| 1161 | |
| 1162 | <div class="summary"> |
| 1163 | <p>In your implementation you should have comments in tricky, |
| 1164 | non-obvious, interesting, or important parts of your code.</p> |
| 1165 | </div> |
| 1166 | |
| 1167 | <div class="stylebody"> |
| 1168 | |
| 1169 | <h4 class="stylepoint_subsection">Explanatory Comments</h4> |
| 1170 | |
| 1171 | <p>Tricky or complicated code blocks should have comments |
| 1172 | before them. Example:</p> |
| 1173 | |
| 1174 | <pre>// Divide result by two, taking into account that x |
| 1175 | // contains the carry from the add. |
| 1176 | for (int i = 0; i < result->size(); i++) { |
| 1177 | x = (x << 8) + (*result)[i]; |
| 1178 | (*result)[i] = x >> 1; |
| 1179 | x &= 1; |
| 1180 | } |
| 1181 | </pre> |
| 1182 | |
| 1183 | <h4 class="stylepoint_subsection">Line Comments</h4> |
| 1184 | |
| 1185 | <p>Also, lines that are non-obvious should get a comment |
| 1186 | at the end of the line. These end-of-line comments should |
| 1187 | be separated from the code by 2 spaces. Example:</p> |
| 1188 | |
| 1189 | <pre>// If we have enough memory, mmap the data portion too. |
| 1190 | mmap_budget = max<int64>(0, mmap_budget - index_->length()); |
| 1191 | if (mmap_budget >= data_size_ && !MmapData(mmap_chunk_bytes, mlock)) |
| 1192 | return; // Error already logged. |
| 1193 | </pre> |
| 1194 | |
| 1195 | <p>Note that there are both comments that describe what |
| 1196 | the code is doing, and comments that mention that an |
| 1197 | error has already been logged when the function |
| 1198 | returns.</p> |
| 1199 | |
| 1200 | <p>If you have several comments on subsequent lines, it |
| 1201 | can often be more readable to line them up:</p> |
| 1202 | |
| 1203 | <pre>DoSomething(); // Comment here so the comments line up. |
| 1204 | DoSomethingElseThatIsLonger(); // Two spaces between the code and the comment. |
| 1205 | { // One space before comment when opening a new scope is allowed, |
| 1206 | // thus the comment lines up with the following comments and code. |
| 1207 | DoSomethingElse(); // Two spaces before line comments normally. |
| 1208 | } |
| 1209 | vector<string> list{// Comments in braced lists describe the next element .. |
| 1210 | "First item", |
| 1211 | // .. and should be aligned appropriately. |
| 1212 | "Second item"}; |
| 1213 | DoSomething(); /* For trailing block comments, one space is fine. */ |
| 1214 | </pre> |
| 1215 | |
| 1216 | <h4 class="stylepoint_subsection">nullptr/NULL, true/false, 1, 2, 3...</h4> |
| 1217 | |
| 1218 | <p>When you pass in a null pointer, boolean, or literal |
| 1219 | integer values to functions, you should consider adding a |
| 1220 | comment about what they are, or make your code |
| 1221 | self-documenting by using constants. For example, |
| 1222 | compare:</p> |
| 1223 | |
| 1224 | <pre class="badcode">bool success = CalculateSomething(interesting_value, |
| 1225 | 10, |
| 1226 | false, |
| 1227 | NULL); // What are these arguments?? |
| 1228 | </pre> |
| 1229 | |
| 1230 | <p>versus:</p> |
| 1231 | |
| 1232 | <pre>bool success = CalculateSomething(interesting_value, |
| 1233 | 10, // Default base value. |
| 1234 | false, // Not the first time we're calling this. |
| 1235 | NULL); // No callback. |
| 1236 | </pre> |
| 1237 | |
| 1238 | <p>Or alternatively, constants or self-describing variables:</p> |
| 1239 | |
| 1240 | <pre>const int kDefaultBaseValue = 10; |
| 1241 | const bool kFirstTimeCalling = false; |
| 1242 | Callback *null_callback = NULL; |
| 1243 | bool success = CalculateSomething(interesting_value, |
| 1244 | kDefaultBaseValue, |
| 1245 | kFirstTimeCalling, |
| 1246 | null_callback); |
| 1247 | </pre> |
| 1248 | |
| 1249 | <h4 class="stylepoint_subsection">Don'ts</h4> |
| 1250 | |
| 1251 | <p>Note that you should <em>never</em> describe the code |
| 1252 | itself. Assume that the person reading the code knows C++ |
| 1253 | better than you do, even though he or she does not know |
| 1254 | what you are trying to do:</p> |
| 1255 | |
| 1256 | <pre class="badcode">// Now go through the b array and make sure that if i occurs, |
| 1257 | // the next element is i+1. |
| 1258 | ... // Geez. What a useless comment. |
| 1259 | </pre> |
| 1260 | |
| 1261 | </div> |
| 1262 | |
| 1263 | <h3 id="Punctuation,_Spelling_and_Grammar">Punctuation, Spelling and Grammar</h3> |
| 1264 | |
| 1265 | <div class="summary"> |
| 1266 | <p>Pay attention to punctuation, spelling, and grammar; it is |
| 1267 | easier to read well-written comments than badly written |
| 1268 | ones.</p> |
| 1269 | </div> |
| 1270 | |
| 1271 | <div class="stylebody"> |
| 1272 | |
| 1273 | <p>Comments should be as readable as narrative text, with |
| 1274 | proper capitalization and punctuation. In many cases, |
| 1275 | complete sentences are more readable than sentence |
| 1276 | fragments. Shorter comments, such as comments at the end |
| 1277 | of a line of code, can sometimes be less formal, but you |
| 1278 | should be consistent with your style.</p> |
| 1279 | |
| 1280 | <p>Although it can be frustrating to have a code reviewer |
| 1281 | point out that you are using a comma when you should be |
| 1282 | using a semicolon, it is very important that source code |
| 1283 | maintain a high level of clarity and readability. Proper |
| 1284 | punctuation, spelling, and grammar help with that |
| 1285 | goal.</p> |
| 1286 | |
| 1287 | </div> |
| 1288 | |
| 1289 | <h3 id="TODO_Comments">TODO Comments</h3> |
| 1290 | |
| 1291 | <div class="summary"> |
| 1292 | <p>Use <code>TODO</code> comments for code that is temporary, |
| 1293 | a short-term solution, or good-enough but not perfect.</p> |
| 1294 | </div> |
| 1295 | |
| 1296 | <div class="stylebody"> |
| 1297 | |
| 1298 | <p><code>TODO</code>s should include the string |
| 1299 | <code>TODO</code> in all caps, followed by the |
| 1300 | |
| 1301 | name, e-mail address, or other |
| 1302 | identifier of the person |
| 1303 | with the best context |
| 1304 | about the problem referenced by the <code>TODO</code>. The |
| 1305 | main purpose is to have a consistent <code>TODO</code> that |
| 1306 | can be searched to find out how to get more details upon |
| 1307 | request. A <code>TODO</code> is not a commitment that the |
| 1308 | person referenced will fix the problem. Thus when you create |
| 1309 | a <code>TODO</code>, it is almost always your |
| 1310 | |
| 1311 | name |
| 1312 | that is given.</p> |
| 1313 | |
| 1314 | |
| 1315 | |
| 1316 | <div> |
| 1317 | <pre>// TODO(kl@gmail.com): Use a "*" here for concatenation operator. |
| 1318 | // TODO(Zeke) change this to use relations. |
| 1319 | </pre> |
| 1320 | </div> |
| 1321 | |
| 1322 | <p>If your <code>TODO</code> is of the form "At a future |
| 1323 | date do something" make sure that you either include a |
| 1324 | very specific date ("Fix by November 2005") or a very |
| 1325 | specific event ("Remove this code when all clients can |
| 1326 | handle XML responses.").</p> |
| 1327 | |
| 1328 | </div> |
| 1329 | |
| 1330 | <h3 id="Deprecation_Comments">Deprecation Comments</h3> |
| 1331 | |
| 1332 | <div class="summary"> |
| 1333 | <p>Mark deprecated interface points with <code>DEPRECATED</code> |
| 1334 | comments.</p> |
| 1335 | </div> |
| 1336 | |
| 1337 | <div class="stylebody"> |
| 1338 | |
| 1339 | <p>You can mark an interface as deprecated by writing a |
| 1340 | comment containing the word <code>DEPRECATED</code> in |
| 1341 | all caps. The comment goes either before the declaration |
| 1342 | of the interface or on the same line as the |
| 1343 | declaration.</p> |
| 1344 | |
| 1345 | |
| 1346 | |
| 1347 | <p>After the word |
| 1348 | <code>DEPRECATED</code>, write your name, e-mail address, |
| 1349 | or other identifier in parentheses.</p> |
| 1350 | |
| 1351 | <p>A deprecation comment must include simple, clear |
| 1352 | directions for people to fix their callsites. In C++, you |
| 1353 | can implement a deprecated function as an inline function |
| 1354 | that calls the new interface point.</p> |
| 1355 | |
| 1356 | <p>Marking an interface point <code>DEPRECATED</code> |
| 1357 | will not magically cause any callsites to change. If you |
| 1358 | want people to actually stop using the deprecated |
| 1359 | facility, you will have to fix the callsites yourself or |
| 1360 | recruit a crew to help you.</p> |
| 1361 | |
| 1362 | <p>New code should not contain calls to deprecated |
| 1363 | interface points. Use the new interface point instead. If |
| 1364 | you cannot understand the directions, find the person who |
| 1365 | created the deprecation and ask them for help using the |
| 1366 | new interface point.</p> |
| 1367 | |
| 1368 | |
| 1369 | |
| 1370 | </div> |
| 1371 | |
| 1372 | <h2 id="Formatting">Formatting</h2> |
| 1373 | |
| 1374 | <p>Coding style and formatting are pretty arbitrary, but a |
| 1375 | |
| 1376 | project is much easier to follow |
| 1377 | if everyone uses the same style. Individuals may not agree with every |
| 1378 | aspect of the formatting rules, and some of the rules may take |
| 1379 | some getting used to, but it is important that all |
| 1380 | |
| 1381 | project contributors follow the |
| 1382 | style rules so that |
| 1383 | they can all read and understand |
| 1384 | everyone's code easily.</p> |
| 1385 | |
| 1386 | |
| 1387 | |
| 1388 | <p>To help you format code correctly, we've |
| 1389 | created a |
| 1390 | <a href="http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el"> |
| 1391 | settings file for emacs</a>.</p> |
| 1392 | |
| 1393 | <h3 id="Line_Length">Line Length</h3> |
| 1394 | |
| 1395 | <div class="summary"> |
| 1396 | <p>Each line of text in your code should be at most 80 |
| 1397 | characters long.</p> |
| 1398 | </div> |
| 1399 | |
| 1400 | <div class="stylebody"> |
| 1401 | |
| 1402 | |
| 1403 | |
| 1404 | <p>We recognize that this rule is |
| 1405 | controversial, but so much existing code already adheres |
| 1406 | to it, and we feel that consistency is important.</p> |
| 1407 | |
| 1408 | <div class="pros"> |
| 1409 | <p>Those who favor this rule |
| 1410 | argue that it is rude to force them to resize |
| 1411 | their windows and there is no need for anything longer. |
| 1412 | Some folks are used to having several code windows |
| 1413 | side-by-side, and thus don't have room to widen their |
| 1414 | windows in any case. People set up their work environment |
| 1415 | assuming a particular maximum window width, and 80 |
| 1416 | columns has been the traditional standard. Why change |
| 1417 | it?</p> |
| 1418 | </div> |
| 1419 | |
| 1420 | <div class="cons"> |
| 1421 | <p>Proponents of change argue that a wider line can make |
| 1422 | code more readable. The 80-column limit is an hidebound |
| 1423 | throwback to 1960s mainframes; modern equipment has wide screens that |
| 1424 | can easily show longer lines.</p> |
| 1425 | </div> |
| 1426 | |
| 1427 | <div class="decision"> |
| 1428 | <p> 80 characters is the maximum.</p> |
| 1429 | |
| 1430 | <p class="exception">If a comment line contains an example |
| 1431 | command or a literal URL longer than 80 characters, that |
| 1432 | line may be longer than 80 characters for ease of cut and |
| 1433 | paste.</p> |
| 1434 | |
| 1435 | <p class="exception">A raw-string literal may have content |
| 1436 | that exceeds 80 characters. Except for test code, such literals |
| 1437 | should appear near top of a file.</p> |
| 1438 | |
| 1439 | <p class="exception">An <code>#include</code> statement with a |
| 1440 | long path may exceed 80 columns.</p> |
| 1441 | |
| 1442 | <p class="exception">You needn't be concerned about |
| 1443 | <a href="#The__define_Guard">header guards</a> that exceed |
| 1444 | the maximum length. </p> |
| 1445 | </div> |
| 1446 | |
| 1447 | </div> |
| 1448 | |
| 1449 | <h3 id="Non-ASCII_Characters">Non-ASCII Characters</h3> |
| 1450 | |
| 1451 | <div class="summary"> |
| 1452 | <p>Non-ASCII characters should be rare, and must use UTF-8 |
| 1453 | formatting.</p> |
| 1454 | </div> |
| 1455 | |
| 1456 | <div class="stylebody"> |
| 1457 | |
| 1458 | <p>You shouldn't hard-code user-facing text in source, |
| 1459 | even English, so use of non-ASCII characters should be |
| 1460 | rare. However, in certain cases it is appropriate to |
| 1461 | include such words in your code. For example, if your |
| 1462 | code parses data files from foreign sources, it may be |
| 1463 | appropriate to hard-code the non-ASCII string(s) used in |
| 1464 | those data files as delimiters. More commonly, unittest |
| 1465 | code (which does not need to be localized) might |
| 1466 | contain non-ASCII strings. In such cases, you should use |
| 1467 | UTF-8, since that is an encoding |
| 1468 | understood by most tools able to handle more than just |
| 1469 | ASCII.</p> |
| 1470 | |
| 1471 | <p>Hex encoding is also OK, and encouraged where it |
| 1472 | enhances readability — for example, |
| 1473 | <code>"\xEF\xBB\xBF"</code>, or, even more simply, |
| 1474 | <code>u8"\uFEFF"</code>, is the Unicode zero-width |
| 1475 | no-break space character, which would be invisible if |
| 1476 | included in the source as straight UTF-8.</p> |
| 1477 | |
| 1478 | <p>Use the <code>u8</code> prefix |
| 1479 | to guarantee that a string literal containing |
| 1480 | <code>\uXXXX</code> escape sequences is encoded as UTF-8. |
| 1481 | Do not use it for strings containing non-ASCII characters |
| 1482 | encoded as UTF-8, because that will produce incorrect |
| 1483 | output if the compiler does not interpret the source file |
| 1484 | as UTF-8. </p> |
| 1485 | |
| 1486 | <p>You shouldn't use the C++11 <code>char16_t</code> and |
| 1487 | <code>char32_t</code> character types, since they're for |
| 1488 | non-UTF-8 text. For similar reasons you also shouldn't |
| 1489 | use <code>wchar_t</code> (unless you're writing code that |
| 1490 | interacts with the Windows API, which uses |
| 1491 | <code>wchar_t</code> extensively).</p> |
| 1492 | |
| 1493 | </div> |
| 1494 | |
| 1495 | <h3 id="Spaces_vs._Tabs">Spaces vs. Tabs</h3> |
| 1496 | |
| 1497 | <div class="summary"> |
| 1498 | <p>Use only spaces, and indent 2 spaces at a time.</p> |
| 1499 | </div> |
| 1500 | |
| 1501 | <div class="stylebody"> |
| 1502 | |
| 1503 | <p>We use spaces for indentation. Do not use tabs in your |
| 1504 | code. You should set your editor to emit spaces when you |
| 1505 | hit the tab key.</p> |
| 1506 | |
| 1507 | </div> |
| 1508 | |
| 1509 | <h3 id="Function_Declarations_and_Definitions">Function Declarations and Definitions</h3> |
| 1510 | |
| 1511 | <div class="summary"> |
| 1512 | <p>Return type on the same line as function name, parameters |
| 1513 | on the same line if they fit. Wrap parameter lists which do |
| 1514 | not fit on a single line as you would wrap arguments in a |
| 1515 | function call.</p> |
| 1516 | </div> |
| 1517 | |
| 1518 | <div class="stylebody"> |
| 1519 | |
| 1520 | <p>Functions look like this:</p> |
| 1521 | |
| 1522 | |
| 1523 | <pre>ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) { |
| 1524 | DoSomething(); |
| 1525 | ... |
| 1526 | } |
| 1527 | </pre> |
| 1528 | |
| 1529 | <p>If you have too much text to fit on one line:</p> |
| 1530 | |
| 1531 | <pre>ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2, |
| 1532 | Type par_name3) { |
| 1533 | DoSomething(); |
| 1534 | ... |
| 1535 | } |
| 1536 | </pre> |
| 1537 | |
| 1538 | <p>or if you cannot fit even the first parameter:</p> |
| 1539 | |
| 1540 | <pre>ReturnType LongClassName::ReallyReallyReallyLongFunctionName( |
| 1541 | Type par_name1, // 4 space indent |
| 1542 | Type par_name2, |
| 1543 | Type par_name3) { |
| 1544 | DoSomething(); // 2 space indent |
| 1545 | ... |
| 1546 | } |
| 1547 | </pre> |
| 1548 | |
| 1549 | <p>Some points to note:</p> |
| 1550 | |
| 1551 | <ul> |
| 1552 | <li>If you cannot fit the return type and the function |
| 1553 | name on a single line, break between them.</li> |
| 1554 | |
| 1555 | <li>If you break after the return type of a function |
| 1556 | declaration or definition, do not indent.</li> |
| 1557 | |
| 1558 | <li>The open parenthesis is always on the same line as |
| 1559 | the function name.</li> |
| 1560 | |
| 1561 | <li>There is never a space between the function name |
| 1562 | and the open parenthesis.</li> |
| 1563 | |
| 1564 | <li>There is never a space between the parentheses and |
| 1565 | the parameters.</li> |
| 1566 | |
| 1567 | <li>The open curly brace is always at the end of the |
| 1568 | same line as the last parameter.</li> |
| 1569 | |
| 1570 | <li>The close curly brace is either on the last line by |
| 1571 | itself or (if other style rules permit) on the same |
| 1572 | line as the open curly brace.</li> |
| 1573 | |
| 1574 | <li>There should be a space between the close |
| 1575 | parenthesis and the open curly brace.</li> |
| 1576 | |
| 1577 | <li>All parameters should be named, with identical |
| 1578 | names in the declaration and implementation.</li> |
| 1579 | |
| 1580 | <li>All parameters should be aligned if possible.</li> |
| 1581 | |
| 1582 | <li>Default indentation is 2 spaces.</li> |
| 1583 | |
| 1584 | <li>Wrapped parameters have a 4 space indent.</li> |
| 1585 | </ul> |
| 1586 | |
| 1587 | <p>If some parameters are unused, comment out the |
| 1588 | variable name in the function definition:</p> |
| 1589 | |
| 1590 | <pre>// Always have named parameters in interfaces. |
| 1591 | class Shape { |
| 1592 | public: |
| 1593 | virtual void Rotate(double radians) = 0; |
| 1594 | }; |
| 1595 | |
| 1596 | // Always have named parameters in the declaration. |
| 1597 | class Circle : public Shape { |
| 1598 | public: |
| 1599 | virtual void Rotate(double radians); |
| 1600 | }; |
| 1601 | |
| 1602 | // Comment out unused named parameters in definitions. |
| 1603 | void Circle::Rotate(double /*radians*/) {} |
| 1604 | </pre> |
| 1605 | |
| 1606 | <pre class="badcode">// Bad - if someone wants to implement later, it's not clear what the |
| 1607 | // variable means. |
| 1608 | void Circle::Rotate(double) {} |
| 1609 | </pre> |
| 1610 | |
| 1611 | </div> |
| 1612 | |
| 1613 | <h3 id="Formatting_Lambda_Expressions">Lambda Expressions</h3> |
| 1614 | |
| 1615 | <div class="summary"> |
| 1616 | <p>Format parameters and bodies as for any other function, and capture |
| 1617 | lists like other comma-separated lists.</p> |
| 1618 | </div> |
| 1619 | |
| 1620 | <div class="stylebody"> |
| 1621 | <p>For by-reference captures, do not leave a space between the |
| 1622 | ampersand (&) and the variable name.</p> |
| 1623 | <pre>int x = 0; |
| 1624 | auto add_to_x = [&x](int n) { x += n; }; |
| 1625 | </pre> |
| 1626 | <p>Short lambdas may be written inline as function arguments.</p> |
| 1627 | <pre>std::set<int> blacklist = {7, 8, 9}; |
| 1628 | std::vector<int> digits = {3, 9, 1, 8, 4, 7, 1}; |
| 1629 | digits.erase(std::remove_if(digits.begin(), digits.end(), [&blacklist](int i) { |
| 1630 | return blacklist.find(i) != blacklist.end(); |
| 1631 | }), |
| 1632 | digits.end()); |
| 1633 | </pre> |
| 1634 | |
| 1635 | </div> |
| 1636 | |
| 1637 | <h3 id="Function_Calls">Function Calls</h3> |
| 1638 | |
| 1639 | <div class="summary"> |
| 1640 | <p>Either write the call all on a single line, wrap the |
| 1641 | arguments at the parenthesis, or start the arguments on a new |
| 1642 | line indented by four spaces and continue at that 4 space |
| 1643 | indent. In the absence of other considerations, use the |
| 1644 | minimum number of lines, including placing multiple arguments |
| 1645 | on each line where appropriate.</p> |
| 1646 | </div> |
| 1647 | |
| 1648 | <div class="stylebody"> |
| 1649 | |
| 1650 | <p>Function calls have the following format:</p> |
| 1651 | <pre>bool retval = DoSomething(argument1, argument2, argument3); |
| 1652 | </pre> |
| 1653 | |
| 1654 | <p>If the arguments do not all fit on one line, they |
| 1655 | should be broken up onto multiple lines, with each |
| 1656 | subsequent line aligned with the first argument. Do not |
| 1657 | add spaces after the open paren or before the close |
| 1658 | paren:</p> |
| 1659 | <pre>bool retval = DoSomething(averyveryveryverylongargument1, |
| 1660 | argument2, argument3); |
| 1661 | </pre> |
| 1662 | |
| 1663 | <p>Arguments may optionally all be placed on subsequent |
| 1664 | lines with a four space indent:</p> |
| 1665 | <pre>if (...) { |
| 1666 | ... |
| 1667 | ... |
| 1668 | if (...) { |
| 1669 | DoSomething( |
| 1670 | argument1, argument2, // 4 space indent |
| 1671 | argument3, argument4); |
| 1672 | } |
| 1673 | </pre> |
| 1674 | |
| 1675 | <p>Put multiple arguments on a single line to reduce the |
| 1676 | number of lines necessary for calling a function unless |
| 1677 | there is a specific readability problem. Some find that |
| 1678 | formatting with strictly one argument on each line is |
| 1679 | more readable and simplifies editing of the arguments. |
| 1680 | However, we prioritize for the reader over the ease of |
| 1681 | editing arguments, and most readability problems are |
| 1682 | better addressed with the following techniques.</p> |
| 1683 | |
| 1684 | <p>If having multiple arguments in a single line decreases |
| 1685 | readability due to the complexity or confusing nature of the |
| 1686 | expressions that make up some arguments, try creating |
| 1687 | variables that capture those arguments in a descriptive name:</p> |
| 1688 | <pre>int my_heuristic = scores[x] * y + bases[x]; |
| 1689 | bool retval = DoSomething(my_heuristic, x, y, z); |
| 1690 | </pre> |
| 1691 | |
| 1692 | <p>Or put the confusing argument on its own line with |
| 1693 | an explanatory comment:</p> |
| 1694 | <pre>bool retval = DoSomething(scores[x] * y + bases[x], // Score heuristic. |
| 1695 | x, y, z); |
| 1696 | </pre> |
| 1697 | |
| 1698 | <p>If there is still a case where one argument is |
| 1699 | significantly more readable on its own line, then put it on |
| 1700 | its own line. The decision should be specific to the argument |
| 1701 | which is made more readable rather than a general policy.</p> |
| 1702 | |
| 1703 | <p>Sometimes arguments form a structure that is important |
| 1704 | for readability. In those cases, feel free to format the |
| 1705 | arguments according to that structure:</p> |
| 1706 | <pre>// Transform the widget by a 3x3 matrix. |
| 1707 | my_widget.Transform(x1, x2, x3, |
| 1708 | y1, y2, y3, |
| 1709 | z1, z2, z3); |
| 1710 | </pre> |
| 1711 | |
| 1712 | </div> |
| 1713 | |
| 1714 | <h3 id="Braced_Initializer_List_Format">Braced Initializer List Format</h3> |
| 1715 | |
| 1716 | <div class="summary"> |
| 1717 | <p>Format a <a href="#Braced_Initializer_List">braced initializer list</a> |
| 1718 | exactly like you would format a function call in its place.</p> |
| 1719 | </div> |
| 1720 | |
| 1721 | <div class="stylebody"> |
| 1722 | |
| 1723 | <p>If the braced list follows a name (e.g. a type or |
| 1724 | variable name), format as if the <code>{}</code> were the |
| 1725 | parentheses of a function call with that name. If there |
| 1726 | is no name, assume a zero-length name.</p> |
| 1727 | |
| 1728 | <pre>// Examples of braced init list on a single line. |
| 1729 | return {foo, bar}; |
| 1730 | functioncall({foo, bar}); |
| 1731 | pair<int, int> p{foo, bar}; |
| 1732 | |
| 1733 | // When you have to wrap. |
| 1734 | SomeFunction( |
| 1735 | {"assume a zero-length name before {"}, |
| 1736 | some_other_function_parameter); |
| 1737 | SomeType variable{ |
| 1738 | some, other, values, |
| 1739 | {"assume a zero-length name before {"}, |
| 1740 | SomeOtherType{ |
| 1741 | "Very long string requiring the surrounding breaks.", |
| 1742 | some, other values}, |
| 1743 | SomeOtherType{"Slightly shorter string", |
| 1744 | some, other, values}}; |
| 1745 | SomeType variable{ |
| 1746 | "This is too long to fit all in one line"}; |
| 1747 | MyType m = { // Here, you could also break before {. |
| 1748 | superlongvariablename1, |
| 1749 | superlongvariablename2, |
| 1750 | {short, interior, list}, |
| 1751 | {interiorwrappinglist, |
| 1752 | interiorwrappinglist2}}; |
| 1753 | </pre> |
| 1754 | |
| 1755 | </div> |
| 1756 | |
| 1757 | <h3 id="Conditionals">Conditionals</h3> |
| 1758 | |
| 1759 | <div class="summary"> |
| 1760 | <p>Prefer no spaces inside parentheses. The <code>if</code> |
| 1761 | and <code>else</code> keywords belong on separate lines.</p> |
| 1762 | </div> |
| 1763 | |
| 1764 | <div class="stylebody"> |
| 1765 | |
| 1766 | <p>There are two acceptable formats for a basic |
| 1767 | conditional statement. One includes spaces between the |
| 1768 | parentheses and the condition, and one does not.</p> |
| 1769 | |
| 1770 | <p>The most common form is without spaces. Either is |
| 1771 | fine, but <em>be consistent</em>. If you are modifying a |
| 1772 | file, use the format that is already present. If you are |
| 1773 | writing new code, use the format that the other files in |
| 1774 | that directory or project use. If in doubt and you have |
| 1775 | no personal preference, do not add the spaces.</p> |
| 1776 | |
| 1777 | <pre>if (condition) { // no spaces inside parentheses |
| 1778 | ... // 2 space indent. |
| 1779 | } else if (...) { // The else goes on the same line as the closing brace. |
| 1780 | ... |
| 1781 | } else { |
| 1782 | ... |
| 1783 | } |
| 1784 | </pre> |
| 1785 | |
| 1786 | <p>If you prefer you may add spaces inside the |
| 1787 | parentheses:</p> |
| 1788 | |
| 1789 | <pre>if ( condition ) { // spaces inside parentheses - rare |
| 1790 | ... // 2 space indent. |
| 1791 | } else { // The else goes on the same line as the closing brace. |
| 1792 | ... |
| 1793 | } |
| 1794 | </pre> |
| 1795 | |
| 1796 | <p>Note that in all cases you must have a space between |
| 1797 | the <code>if</code> and the open parenthesis. You must |
| 1798 | also have a space between the close parenthesis and the |
| 1799 | curly brace, if you're using one.</p> |
| 1800 | |
| 1801 | <pre class="badcode">if(condition) { // Bad - space missing after IF. |
| 1802 | if (condition){ // Bad - space missing before {. |
| 1803 | if(condition){ // Doubly bad. |
| 1804 | </pre> |
| 1805 | |
| 1806 | <pre>if (condition) { // Good - proper space after IF and before {. |
| 1807 | </pre> |
| 1808 | |
| 1809 | <p>Short conditional statements may be written on one |
| 1810 | line if this enhances readability. You may use this only |
| 1811 | when the line is brief and the statement does not use the |
| 1812 | <code>else</code> clause.</p> |
| 1813 | |
| 1814 | <pre>if (x == kFoo) return new Foo(); |
| 1815 | if (x == kBar) return new Bar(); |
| 1816 | </pre> |
| 1817 | |
| 1818 | <p>This is not allowed when the if statement has an |
| 1819 | <code>else</code>:</p> |
| 1820 | |
| 1821 | <pre class="badcode">// Not allowed - IF statement on one line when there is an ELSE clause |
| 1822 | if (x) DoThis(); |
| 1823 | else DoThat(); |
| 1824 | </pre> |
| 1825 | |
| 1826 | <p>In general, curly braces are not required for |
| 1827 | single-line statements, but they are allowed if you like |
| 1828 | them; conditional or loop statements with complex |
| 1829 | conditions or statements may be more readable with curly |
| 1830 | braces. Some |
| 1831 | projects require that an |
| 1832 | <code>if</code> must always always have an accompanying |
| 1833 | brace.</p> |
| 1834 | |
| 1835 | <pre>if (condition) |
| 1836 | DoSomething(); // 2 space indent. |
| 1837 | |
| 1838 | if (condition) { |
| 1839 | DoSomething(); // 2 space indent. |
| 1840 | } |
| 1841 | </pre> |
| 1842 | |
| 1843 | <p>However, if one part of an |
| 1844 | <code>if</code>-<code>else</code> statement uses curly |
| 1845 | braces, the other part must too:</p> |
| 1846 | |
| 1847 | <pre class="badcode">// Not allowed - curly on IF but not ELSE |
| 1848 | if (condition) { |
| 1849 | foo; |
| 1850 | } else |
| 1851 | bar; |
| 1852 | |
| 1853 | // Not allowed - curly on ELSE but not IF |
| 1854 | if (condition) |
| 1855 | foo; |
| 1856 | else { |
| 1857 | bar; |
| 1858 | } |
| 1859 | </pre> |
| 1860 | |
| 1861 | <pre>// Curly braces around both IF and ELSE required because |
| 1862 | // one of the clauses used braces. |
| 1863 | if (condition) { |
| 1864 | foo; |
| 1865 | } else { |
| 1866 | bar; |
| 1867 | } |
| 1868 | </pre> |
| 1869 | |
| 1870 | </div> |
| 1871 | |
| 1872 | <h3 id="Loops_and_Switch_Statements">Loops and Switch Statements</h3> |
| 1873 | |
| 1874 | <div class="summary"> |
| 1875 | <p>Switch statements may use braces for blocks. Annotate |
| 1876 | non-trivial fall-through between cases. |
| 1877 | Braces are optional for single-statement loops. |
| 1878 | Empty loop bodies should use <code>{}</code> or <code>continue</code>.</p> |
| 1879 | </div> |
| 1880 | |
| 1881 | <div class="stylebody"> |
| 1882 | |
| 1883 | <p><code>case</code> blocks in <code>switch</code> |
| 1884 | statements can have curly braces or not, depending on |
| 1885 | your preference. If you do include curly braces they |
| 1886 | should be placed as shown below.</p> |
| 1887 | |
| 1888 | <p>If not conditional on an enumerated value, switch |
| 1889 | statements should always have a <code>default</code> case |
| 1890 | (in the case of an enumerated value, the compiler will |
| 1891 | warn you if any values are not handled). If the default |
| 1892 | case should never execute, simply |
| 1893 | <code>assert</code>:</p> |
| 1894 | |
| 1895 | |
| 1896 | |
| 1897 | <div> |
| 1898 | <pre>switch (var) { |
| 1899 | case 0: { // 2 space indent |
| 1900 | ... // 4 space indent |
| 1901 | break; |
| 1902 | } |
| 1903 | case 1: { |
| 1904 | ... |
| 1905 | break; |
| 1906 | } |
| 1907 | default: { |
| 1908 | assert(false); |
| 1909 | } |
| 1910 | } |
| 1911 | </pre> |
| 1912 | </div> |
| 1913 | |
| 1914 | |
| 1915 | |
| 1916 | |
| 1917 | |
| 1918 | <p> Braces are optional for single-statement loops.</p> |
| 1919 | |
| 1920 | <pre>for (int i = 0; i < kSomeNumber; ++i) |
| 1921 | printf("I love you\n"); |
| 1922 | |
| 1923 | for (int i = 0; i < kSomeNumber; ++i) { |
| 1924 | printf("I take it back\n"); |
| 1925 | } |
| 1926 | </pre> |
| 1927 | |
| 1928 | |
| 1929 | <p>Empty loop bodies should use <code>{}</code> or |
| 1930 | <code>continue</code>, but not a single semicolon.</p> |
| 1931 | |
| 1932 | <pre>while (condition) { |
| 1933 | // Repeat test until it returns false. |
| 1934 | } |
| 1935 | for (int i = 0; i < kSomeNumber; ++i) {} // Good - empty body. |
| 1936 | while (condition) continue; // Good - continue indicates no logic. |
| 1937 | </pre> |
| 1938 | |
| 1939 | <pre class="badcode">while (condition); // Bad - looks like part of do/while loop. |
| 1940 | </pre> |
| 1941 | |
| 1942 | </div> |
| 1943 | |
| 1944 | <h3 id="Pointer_and_Reference_Expressions">Pointer and Reference Expressions</h3> |
| 1945 | |
| 1946 | <div class="summary"> |
| 1947 | <p>No spaces around period or arrow. Pointer operators do not |
| 1948 | have trailing spaces.</p> |
| 1949 | </div> |
| 1950 | |
| 1951 | <div class="stylebody"> |
| 1952 | |
| 1953 | <p>The following are examples of correctly-formatted |
| 1954 | pointer and reference expressions:</p> |
| 1955 | |
| 1956 | <pre>x = *p; |
| 1957 | p = &x; |
| 1958 | x = r.y; |
| 1959 | x = r->y; |
| 1960 | </pre> |
| 1961 | |
| 1962 | <p>Note that:</p> |
| 1963 | |
| 1964 | <ul> |
| 1965 | <li>There are no spaces around the period or arrow when |
| 1966 | accessing a member.</li> |
| 1967 | |
| 1968 | <li>Pointer operators have no space after the |
| 1969 | <code>*</code> or <code>&</code>.</li> |
| 1970 | </ul> |
| 1971 | |
| 1972 | <p>When declaring a pointer variable or argument, you may |
| 1973 | place the asterisk adjacent to either the type or to the |
| 1974 | variable name:</p> |
| 1975 | |
| 1976 | <pre>// These are fine, space preceding. |
| 1977 | char *c; |
| 1978 | const string &str; |
| 1979 | |
| 1980 | // These are fine, space following. |
| 1981 | char* c; // but remember to do "char* c, *d, *e, ...;"! |
| 1982 | const string& str; |
| 1983 | </pre> |
| 1984 | |
| 1985 | <pre class="badcode">char * c; // Bad - spaces on both sides of * |
| 1986 | const string & str; // Bad - spaces on both sides of & |
| 1987 | </pre> |
| 1988 | |
| 1989 | <p>You should do this consistently within a single |
| 1990 | file, |
| 1991 | so, when modifying an existing file, use the style in |
| 1992 | that file.</p> |
| 1993 | |
| 1994 | </div> |
| 1995 | |
| 1996 | <h3 id="Boolean_Expressions">Boolean Expressions</h3> |
| 1997 | |
| 1998 | <div class="summary"> |
| 1999 | <p>When you have a boolean expression that is longer than the |
| 2000 | <a href="#Line_Length">standard line length</a>, be |
| 2001 | consistent in how you break up the lines.</p> |
| 2002 | </div> |
| 2003 | |
| 2004 | <div class="stylebody"> |
| 2005 | |
| 2006 | <p>In this example, the logical AND operator is always at |
| 2007 | the end of the lines:</p> |
| 2008 | |
| 2009 | <pre>if (this_one_thing > this_other_thing && |
| 2010 | a_third_thing == a_fourth_thing && |
| 2011 | yet_another && last_one) { |
| 2012 | ... |
| 2013 | } |
| 2014 | </pre> |
| 2015 | |
| 2016 | <p>Note that when the code wraps in this example, both of |
| 2017 | the <code>&&</code> logical AND operators are at |
| 2018 | the end of the line. This is more common in Google code, |
| 2019 | though wrapping all operators at the beginning of the |
| 2020 | line is also allowed. Feel free to insert extra |
| 2021 | parentheses judiciously because they can be very helpful |
| 2022 | in increasing readability when used |
| 2023 | appropriately. Also note that you should always use |
| 2024 | the punctuation operators, such as |
| 2025 | <code>&&</code> and <code>~</code>, rather than |
| 2026 | the word operators, such as <code>and</code> and |
| 2027 | <code>compl</code>.</p> |
| 2028 | |
| 2029 | </div> |
| 2030 | |
| 2031 | <h3 id="Return_Values">Return Values</h3> |
| 2032 | |
| 2033 | <div class="summary"> |
| 2034 | <p>Do not needlessly surround the <code>return</code> |
| 2035 | expression with parentheses.</p> |
| 2036 | </div> |
| 2037 | |
| 2038 | <div class="stylebody"> |
| 2039 | |
| 2040 | <p>Use parentheses in <code>return expr;</code> only |
| 2041 | where you would use them in <code>x = expr;</code>.</p> |
| 2042 | |
| 2043 | <pre>return result; // No parentheses in the simple case. |
| 2044 | // Parentheses OK to make a complex expression more readable. |
| 2045 | return (some_long_condition && |
| 2046 | another_condition); |
| 2047 | </pre> |
| 2048 | |
| 2049 | <pre class="badcode">return (value); // You wouldn't write var = (value); |
| 2050 | return(result); // return is not a function! |
| 2051 | </pre> |
| 2052 | |
| 2053 | </div> |
| 2054 | |
| 2055 | |
| 2056 | |
| 2057 | <h3 id="Variable_and_Array_Initialization">Variable and Array Initialization</h3> |
| 2058 | |
| 2059 | <div class="summary"> |
| 2060 | <p>Your choice of <code>=</code>, <code>()</code>, or |
| 2061 | <code>{}</code>.</p> |
| 2062 | </div> |
| 2063 | |
| 2064 | <div class="stylebody"> |
| 2065 | |
| 2066 | <p>You may choose between <code>=</code>, |
| 2067 | <code>()</code>, and <code>{}</code>; the following are |
| 2068 | all correct:</p> |
| 2069 | |
| 2070 | <pre>int x = 3; |
| 2071 | int x(3); |
| 2072 | int x{3}; |
| 2073 | string name = "Some Name"; |
| 2074 | string name("Some Name"); |
| 2075 | string name{"Some Name"}; |
| 2076 | </pre> |
| 2077 | |
| 2078 | <p>Be careful when using a braced initialization list <code>{...}</code> |
| 2079 | on a type with an <code>std::initializer_list</code> constructor. |
| 2080 | A nonempty <i>braced-init-list</i> prefers the |
| 2081 | <code>std::initializer_list</code> constructor whenever |
| 2082 | possible. Note that empty braces <code>{}</code> are special, and |
| 2083 | will call a default constructor if available. To force the |
| 2084 | non-<code>std::initializer_list</code> constructor, use parentheses |
| 2085 | instead of braces.</p> |
| 2086 | |
| 2087 | <pre>vector<int> v(100, 1); // A vector of 100 1s. |
| 2088 | vector<int> v{100, 1}; // A vector of 100, 1. |
| 2089 | </pre> |
| 2090 | |
| 2091 | <p>Also, the brace form prevents narrowing of integral |
| 2092 | types. This can prevent some types of programming |
| 2093 | errors.</p> |
| 2094 | |
| 2095 | <pre>int pi(3.14); // OK -- pi == 3. |
| 2096 | int pi{3.14}; // Compile error: narrowing conversion. |
| 2097 | </pre> |
| 2098 | |
| 2099 | </div> |
| 2100 | |
| 2101 | <h3 id="Preprocessor_Directives">Preprocessor Directives</h3> |
| 2102 | |
| 2103 | <div class="summary"> |
| 2104 | <p>The hash mark that starts a preprocessor directive should |
| 2105 | always be at the beginning of the line.</p> |
| 2106 | </div> |
| 2107 | |
| 2108 | <div class="stylebody"> |
| 2109 | |
| 2110 | <p>Even when preprocessor directives are within the body |
| 2111 | of indented code, the directives should start at the |
| 2112 | beginning of the line.</p> |
| 2113 | |
| 2114 | <pre>// Good - directives at beginning of line |
| 2115 | if (lopsided_score) { |
| 2116 | #if DISASTER_PENDING // Correct -- Starts at beginning of line |
| 2117 | DropEverything(); |
| 2118 | # if NOTIFY // OK but not required -- Spaces after # |
| 2119 | NotifyClient(); |
| 2120 | # endif |
| 2121 | #endif |
| 2122 | BackToNormal(); |
| 2123 | } |
| 2124 | </pre> |
| 2125 | |
| 2126 | <pre class="badcode">// Bad - indented directives |
| 2127 | if (lopsided_score) { |
| 2128 | #if DISASTER_PENDING // Wrong! The "#if" should be at beginning of line |
| 2129 | DropEverything(); |
| 2130 | #endif // Wrong! Do not indent "#endif" |
| 2131 | BackToNormal(); |
| 2132 | } |
| 2133 | </pre> |
| 2134 | |
| 2135 | </div> |
| 2136 | |
| 2137 | <h3 id="Class_Format">Class Format</h3> |
| 2138 | |
| 2139 | <div class="summary"> |
| 2140 | <p>Sections in <code>public</code>, <code>protected</code> and |
| 2141 | <code>private</code> order, each indented one space.</p> |
| 2142 | </div> |
| 2143 | |
| 2144 | <div class="stylebody"> |
| 2145 | |
| 2146 | <p>The basic format for a class declaration (lacking the |
| 2147 | comments, see <a href="#Class_Comments">Class |
| 2148 | Comments</a> for a discussion of what comments are |
| 2149 | needed) is:</p> |
| 2150 | |
| 2151 | <pre>class MyClass : public OtherClass { |
| 2152 | public: // Note the 1 space indent! |
| 2153 | MyClass(); // Regular 2 space indent. |
| 2154 | explicit MyClass(int var); |
| 2155 | ~MyClass() {} |
| 2156 | |
| 2157 | void SomeFunction(); |
| 2158 | void SomeFunctionThatDoesNothing() { |
| 2159 | } |
| 2160 | |
| 2161 | void set_some_var(int var) { some_var_ = var; } |
| 2162 | int some_var() const { return some_var_; } |
| 2163 | |
| 2164 | private: |
| 2165 | bool SomeInternalFunction(); |
| 2166 | |
| 2167 | int some_var_; |
| 2168 | int some_other_var_; |
| 2169 | }; |
| 2170 | </pre> |
| 2171 | |
| 2172 | <p>Things to note:</p> |
| 2173 | |
| 2174 | <ul> |
| 2175 | <li>Any base class name should be on the same line as |
| 2176 | the subclass name, subject to the 80-column limit.</li> |
| 2177 | |
| 2178 | <li>The <code>public:</code>, <code>protected:</code>, |
| 2179 | and <code>private:</code> keywords should be indented |
| 2180 | one space.</li> |
| 2181 | |
| 2182 | <li>Except for the first instance, these keywords |
| 2183 | should be preceded by a blank line. This rule is |
| 2184 | optional in small classes.</li> |
| 2185 | |
| 2186 | <li>Do not leave a blank line after these |
| 2187 | keywords.</li> |
| 2188 | |
| 2189 | <li>The <code>public</code> section should be first, |
| 2190 | followed by the <code>protected</code> and finally the |
| 2191 | <code>private</code> section.</li> |
| 2192 | |
| 2193 | <li>See <a href="#Declaration_Order">Declaration |
| 2194 | Order</a> for rules on ordering declarations within |
| 2195 | each of these sections.</li> |
| 2196 | </ul> |
| 2197 | |
| 2198 | </div> |
| 2199 | |
| 2200 | <h3 id="Constructor_Initializer_Lists">Constructor Initializer Lists</h3> |
| 2201 | |
| 2202 | <div class="summary"> |
| 2203 | <p>Constructor initializer lists can be all on one line or |
| 2204 | with subsequent lines indented four spaces.</p> |
| 2205 | </div> |
| 2206 | |
| 2207 | <div class="stylebody"> |
| 2208 | |
| 2209 | <p>There are two acceptable formats for initializer |
| 2210 | lists:</p> |
| 2211 | |
| 2212 | <pre>// When it all fits on one line: |
| 2213 | MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {} |
| 2214 | </pre> |
| 2215 | |
| 2216 | <p>or</p> |
| 2217 | |
| 2218 | <pre>// When it requires multiple lines, indent 4 spaces, putting the colon on |
| 2219 | // the first initializer line: |
| 2220 | MyClass::MyClass(int var) |
| 2221 | : some_var_(var), // 4 space indent |
| 2222 | some_other_var_(var + 1) { // lined up |
| 2223 | ... |
| 2224 | DoSomething(); |
| 2225 | ... |
| 2226 | } |
| 2227 | </pre> |
| 2228 | |
| 2229 | </div> |
| 2230 | |
| 2231 | <h3 id="Namespace_Formatting">Namespace Formatting</h3> |
| 2232 | |
| 2233 | <div class="summary"> |
| 2234 | <p>The contents of namespaces are not indented.</p> |
| 2235 | </div> |
| 2236 | |
| 2237 | <div class="stylebody"> |
| 2238 | |
| 2239 | <p><a href="#Namespaces">Namespaces</a> do not add an |
| 2240 | extra level of indentation. For example, use:</p> |
| 2241 | |
| 2242 | <pre>namespace { |
| 2243 | |
| 2244 | void foo() { // Correct. No extra indentation within namespace. |
| 2245 | ... |
| 2246 | } |
| 2247 | |
| 2248 | } // namespace |
| 2249 | </pre> |
| 2250 | |
| 2251 | <p>Do not indent within a namespace:</p> |
| 2252 | |
| 2253 | <pre class="badcode">namespace { |
| 2254 | |
| 2255 | // Wrong. Indented when it should not be. |
| 2256 | void foo() { |
| 2257 | ... |
| 2258 | } |
| 2259 | |
| 2260 | } // namespace |
| 2261 | </pre> |
| 2262 | |
| 2263 | <p>When declaring nested namespaces, put each namespace |
| 2264 | on its own line.</p> |
| 2265 | |
| 2266 | <pre>namespace foo { |
| 2267 | namespace bar { |
| 2268 | </pre> |
| 2269 | |
| 2270 | </div> |
| 2271 | |
| 2272 | <h3 id="Horizontal_Whitespace">Horizontal Whitespace</h3> |
| 2273 | |
| 2274 | <div class="summary"> |
| 2275 | <p>Use of horizontal whitespace depends on location. Never put |
| 2276 | trailing whitespace at the end of a line.</p> |
| 2277 | </div> |
| 2278 | |
| 2279 | <div class="stylebody"> |
| 2280 | |
| 2281 | <h4 class="stylepoint_subsection">General</h4> |
| 2282 | |
| 2283 | <pre>void f(bool b) { // Open braces should always have a space before them. |
| 2284 | ... |
| 2285 | int i = 0; // Semicolons usually have no space before them. |
| 2286 | // Spaces inside braces for braced-init-list are optional. If you use them, |
| 2287 | // put them on both sides! |
| 2288 | int x[] = { 0 }; |
| 2289 | int x[] = {0}; |
| 2290 | |
| 2291 | // Spaces around the colon in inheritance and initializer lists. |
| 2292 | class Foo : public Bar { |
| 2293 | public: |
| 2294 | // For inline function implementations, put spaces between the braces |
| 2295 | // and the implementation itself. |
| 2296 | Foo(int b) : Bar(), baz_(b) {} // No spaces inside empty braces. |
| 2297 | void Reset() { baz_ = 0; } // Spaces separating braces from implementation. |
| 2298 | ... |
| 2299 | </pre> |
| 2300 | |
| 2301 | <p>Adding trailing whitespace can cause extra work for |
| 2302 | others editing the same file, when they merge, as can |
| 2303 | removing existing trailing whitespace. So: Don't |
| 2304 | introduce trailing whitespace. Remove it if you're |
| 2305 | already changing that line, or do it in a separate |
| 2306 | clean-up |
| 2307 | operation (preferably when no-one |
| 2308 | else is working on the file).</p> |
| 2309 | |
| 2310 | <h4 class="stylepoint_subsection">Loops and Conditionals</h4> |
| 2311 | |
| 2312 | <pre>if (b) { // Space after the keyword in conditions and loops. |
| 2313 | } else { // Spaces around else. |
| 2314 | } |
| 2315 | while (test) {} // There is usually no space inside parentheses. |
| 2316 | switch (i) { |
| 2317 | for (int i = 0; i < 5; ++i) { |
| 2318 | // Loops and conditions may have spaces inside parentheses, but this |
| 2319 | // is rare. Be consistent. |
| 2320 | switch ( i ) { |
| 2321 | if ( test ) { |
| 2322 | for ( int i = 0; i < 5; ++i ) { |
| 2323 | // For loops always have a space after the semicolon. They may have a space |
| 2324 | // before the semicolon, but this is rare. |
| 2325 | for ( ; i < 5 ; ++i) { |
| 2326 | ... |
| 2327 | |
| 2328 | // Range-based for loops always have a space before and after the colon. |
| 2329 | for (auto x : counts) { |
| 2330 | ... |
| 2331 | } |
| 2332 | switch (i) { |
| 2333 | case 1: // No space before colon in a switch case. |
| 2334 | ... |
| 2335 | case 2: break; // Use a space after a colon if there's code after it. |
| 2336 | </pre> |
| 2337 | |
| 2338 | <h4 class="stylepoint_subsection">Operators</h4> |
| 2339 | |
| 2340 | <pre>// Assignment operators always have spaces around them. |
| 2341 | x = 0; |
| 2342 | |
| 2343 | // Other binary operators usually have spaces around them, but it's |
| 2344 | // OK to remove spaces around factors. Parentheses should have no |
| 2345 | // internal padding. |
| 2346 | v = w * x + y / z; |
| 2347 | v = w*x + y/z; |
| 2348 | v = w * (x + z); |
| 2349 | |
| 2350 | // No spaces separating unary operators and their arguments. |
| 2351 | x = -5; |
| 2352 | ++x; |
| 2353 | if (x && !y) |
| 2354 | ... |
| 2355 | </pre> |
| 2356 | |
| 2357 | <h4 class="stylepoint_subsection">Templates and Casts</h4> |
| 2358 | |
| 2359 | <pre>// No spaces inside the angle brackets (< and >), before |
| 2360 | // <, or between >( in a cast |
| 2361 | vector<string> x; |
| 2362 | y = static_cast<char*>(x); |
| 2363 | |
| 2364 | // Spaces between type and pointer are OK, but be consistent. |
| 2365 | vector<char *> x; |
| 2366 | set<list<string>> x; // Permitted in C++11 code. |
| 2367 | set<list<string> > x; // C++03 required a space in > >. |
| 2368 | |
| 2369 | // You may optionally use symmetric spacing in < <. |
| 2370 | set< list<string> > x; |
| 2371 | </pre> |
| 2372 | |
| 2373 | </div> |
| 2374 | |
| 2375 | <h3 id="Vertical_Whitespace">Vertical Whitespace</h3> |
| 2376 | |
| 2377 | <div class="summary"> |
| 2378 | <p>Minimize use of vertical whitespace.</p> |
| 2379 | </div> |
| 2380 | |
| 2381 | <div class="stylebody"> |
| 2382 | |
| 2383 | <p>This is more a principle than a rule: don't use blank |
| 2384 | lines when you don't have to. In particular, don't put |
| 2385 | more than one or two blank lines between functions, |
| 2386 | resist starting functions with a blank line, don't end |
| 2387 | functions with a blank line, and be discriminating with |
| 2388 | your use of blank lines inside functions.</p> |
| 2389 | |
| 2390 | <p>The basic principle is: The more code that fits on one |
| 2391 | screen, the easier it is to follow and understand the |
| 2392 | control flow of the program. Of course, readability can |
| 2393 | suffer from code being too dense as well as too spread |
| 2394 | out, so use your judgement. But in general, minimize use |
| 2395 | of vertical whitespace.</p> |
| 2396 | |
| 2397 | <p>Some rules of thumb to help when blank lines may be |
| 2398 | useful:</p> |
| 2399 | |
| 2400 | <ul> |
| 2401 | <li>Blank lines at the beginning or end of a function |
| 2402 | very rarely help readability.</li> |
| 2403 | |
| 2404 | <li>Blank lines inside a chain of if-else blocks may |
| 2405 | well help readability.</li> |
| 2406 | </ul> |
| 2407 | |
| 2408 | </div> |
| 2409 | |
| 2410 | <h2 id="Exceptions_to_the_Rules">Exceptions to the Rules</h2> |
| 2411 | |
| 2412 | <p>The coding conventions described above are mandatory. |
| 2413 | However, like all good rules, these sometimes have exceptions, |
| 2414 | which we discuss here.</p> |
| 2415 | |
| 2416 | |
| 2417 | |
| 2418 | <div> |
| 2419 | <h3 id="Existing_Non-conformant_Code">Existing Non-conformant Code</h3> |
| 2420 | |
| 2421 | <div class="summary"> |
| 2422 | <p>You may diverge from the rules when dealing with code that |
| 2423 | does not conform to this style guide.</p> |
| 2424 | </div> |
| 2425 | |
| 2426 | <div class="stylebody"> |
| 2427 | |
| 2428 | <p>If you find yourself modifying code that was written |
| 2429 | to specifications other than those presented by this |
| 2430 | guide, you may have to diverge from these rules in order |
| 2431 | to stay consistent with the local conventions in that |
| 2432 | code. If you are in doubt about how to do this, ask the |
| 2433 | original author or the person currently responsible for |
| 2434 | the code. Remember that <em>consistency</em> includes |
| 2435 | local consistency, too.</p> |
| 2436 | |
| 2437 | </div> |
| 2438 | </div> |
| 2439 | |
| 2440 | |
| 2441 | <h2 class="ignoreLink">Parting Words</h2> |
| 2442 | |
| 2443 | <p>Use common sense and <em>BE CONSISTENT</em>.</p> |
| 2444 | |
| 2445 | <p>If you are editing code, take a few minutes to look at the |
| 2446 | code around you and determine its style. If they use spaces |
| 2447 | around their <code>if</code> clauses, you should, too. If their |
| 2448 | comments have little boxes of stars around them, make your |
| 2449 | comments have little boxes of stars around them too.</p> |
| 2450 | |
| 2451 | <p>The point of having style guidelines is to have a common |
| 2452 | vocabulary of coding so people can concentrate on what you are |
| 2453 | saying, rather than on how you are saying it. We present global |
| 2454 | style rules here so people know the vocabulary. But local style |
| 2455 | is also important. If code you add to a file looks drastically |
| 2456 | different from the existing code around it, the discontinuity |
| 2457 | throws readers out of their rhythm when they go to read it. Try |
| 2458 | to avoid this.</p> |
| 2459 | |
| 2460 | |
| 2461 | |
| 2462 | <p>OK, enough writing about writing code; the code itself is much |
| 2463 | more interesting. Have fun!</p> |
| 2464 | |
| 2465 | <hr> |
| 2466 | |
| 2467 | <p style="text-align:right; font-style:italic;">Revision 4.45</p> |
| 2468 | |
| 2469 | </div> |
| 2470 | </body></html> |