blob: f37c836c1da7ff11f0864f590df5cf878cc9f309 [file] [log] [blame]
Brian Silverman1a675112016-02-20 20:42:49 -05001<!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>
19We are currently working on getting this guide updated to
20a 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)
23used in WPILib; in order to maintain consistency and keep the
24maintenance of the code manageable, we use this style guide.</p>
25
26<p>There are two main overarching purposes to this guide. The first
27is to act as a normal C++ style guide (both in terms fo formatting
28and programming practices) for C++ developers of WPILib.
29The other purpose is to help Java programmers who may
30know a moderate amount of C++ but may not be fully
31up to date with things like C++11 and so may not even
32realize 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>
36Google C++ Style Guide</a>. The Google Style Guide has
37a lot of good points and is a good read, but in order
38to cut the style guide down to a more readable size and to
39focus mroe on WPILib-specific information, we have
40altetered the original style guide in several ways.</p>
41
42<p>One way in which we <em>haven't</em> done much to
43alter the original style guide is to keep the vast
44majority of the formatting/naming/etc. related
45information intact. This is both so that we
46do not have to write up our own standards and so
47that existing tools such as clang-format and
48the Google eclipse format configuration files
49can work out of the box. All of these things
50should be relatively non-controversial and do not
51require much discussion.</p>
52
53<p>Where we deviate more from the original guide is
54in the style of the code itself. At the moment (ie,
55when we first created this modified version), we
56deleted all of the sections of the original guide
57which mandate particular programming practices
58such as forbidding exceptions, multiple inheritance,
59etc. However, as time goes on, we gradually add in more
60information along this lines, either by copying
61directly from Google's Style Guide or by writing
62our own decisions and best practices, some of which
63may be very WPILib-specific.</p>
64
65<p>As the original guide makes very clear, consistency
66is extremely important to keeping the code base
67manageable, and so we encourage that, wherever
68reasonable, that you keep everything consistent
69with whatever the standard style is.</p>
70
71<p>Along with just C++ style, it is also important
72to keep in mind that WPILib consists of both a C++
73and Java half. In order to keep things consistent
74and easier for users, we ask that, in general,
75Java and C++ be kept as consistent with one another
76as reasonable. This includes everything from using
77two spaces for indentation in both language to
78keeping the inheritance structure essentially the
79same in both. Although the two do not have to be
80precisely the same, it does mean that if there is
81something that you are doing which will be imposssible
82to reproduce in some way in Java, then you may
83want to reconsider.</p>
84
85<p>One final thing to remember is that High School
86students with relatively little experience programming
87are the main user for this code, and throwing the full
88brunt of C++ at a student just learning how to program
89is likely not the best of ideas. As such, any
90user-facing APIs should minimize the use of any
91more complicated C++ features. As always,
92use your judgement and ask others in cases where
93there is something which may violate anything
94in this guide.</p>
95
96<h2 id="Programming_Guidelines">Programming Guidelines</h2>
97<p>C++ is a large, complicated language, and in order
98to ensure that we stay consistent and maintain certain
99best practices, we have certain rules. For the most part
100these are common sense rules and in some cases exist
101solely to point out features of C++ that someone more
102familiar 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
106raw pointers in C++ code; instead, references or
107STL pointers should be used where appropriate.
108There 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
122place 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
158it is reasonable to simply remove any old interfaces
159then do so) to indicate that users should no longer
160use the function. Currently, this will cause warnings
161in 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.")]]
166void foo() {}
167class [[deprecated("This is a deprecated class.")]] Foo {};
168int bar [[deprecated("This is a deprecated variable.")]];
169</pre>
170
171<p>See <a href=http://josephmansfield.uk/articles/marking-deprecated-c++14.html>
172here</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
177associated <code>.h</code> file. There are some common
178exceptions, such as unittests and
179small <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
183the readability, size and performance of your code.</p>
184
185<p>The following rules will guide you through the various
186pitfalls 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
193are 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
199words, users and refactoring tools should not have to adhere to special
200conditions in order to include the header. Specifically, a
201header should have <a href="#The__define_Guard">header guards</a>,
202should include all other headers it needs, and should not require any
203particular symbols to be defined.</p>
204
205<p>There are rare cases where a file is not meant to be self-contained, but
206instead is meant to be textually included at a specific point in the code.
207Examples are files that need to be included multiple times or
208platform-specific extensions that essentially are part of other headers. Such
209files 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,
212define it in that same file. The definitions of these constructs must
213be included into every <code>.cc</code> file that uses them, or the
214program may fail to link in some build configurations. Do not move these
215definitions to separate <code>-inl.h</code> files.</p>
216
217<p>As an exception, a function template that is explicitly
218instantiated for all relevant sets of template arguments, or
219that is a private member of a class, may
220be defined in the only <code>.cc</code> file that
221instantiates 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
229prevent multiple inclusion. The format of the symbol name
230should be
231<code><i>&lt;PROJECT&gt;</i>_<i>&lt;PATH&gt;</i>_<i>&lt;FILE&gt;</i>_H_</code>.</p>
232</div>
233
234<div class="stylebody">
235
236
237
238<p>To guarantee uniqueness, they should
239be based on the full path in a project's source tree. For
240example, the file <code>foo/src/bar/baz.h</code> in
241project <code>foo</code> should have the following
242guard:</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
261unnecessary <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,
268function, or template without an associated definition.
269<code>#include</code> lines can often be replaced with
270forward declarations of whatever symbols are actually
271used 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
341of 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
350lines 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
357them inline rather than calling them through the usual
358function call mechanism.</p>
359</div>
360
361<div class="pros">
362<p>Inlining a function can generate more efficient object
363code, as long as the inlined function is small. Feel free
364to inline accessors and mutators, and other short,
365performance-critical functions.</p>
366</div>
367
368<div class="cons">
369<p>Overuse of inlining can actually make programs slower.
370Depending on a function's size, inlining it can cause the
371code size to increase or decrease. Inlining a very small
372accessor function will usually decrease code size while
373inlining a very large function can dramatically increase
374code size. On modern processors smaller code usually runs
375faster 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
380it is more than 10 lines long. Beware of destructors,
381which are often longer than they appear because of
382implicit member- and base-destructor calls!</p>
383
384<p>Another useful rule of thumb: it's typically not cost
385effective to inline functions with loops or switch
386statements (unless, in the common case, the loop or
387switch statement is never executed).</p>
388
389<p>It is important to know that functions are not always
390inlined even if they are declared as such; for example,
391virtual and recursive functions are not normally inlined.
392Usually recursive functions should not be inline. The
393main reason for making a virtual function inline is to
394place its definition in the class, either for convenience
395or to document its behavior, e.g., for accessors and
396mutators.</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
405outputs.</p>
406</div>
407
408<div class="stylebody">
409<p>Parameters to C/C++ functions are either input to the
410function, output from the function, or both. Input
411parameters are usually values or <code>const</code>
412references, while output and input/output parameters will
413be non-<code>const</code> pointers. When ordering
414function parameters, put all input-only parameters before
415any output parameters. In particular, do not add new
416parameters to the end of the function just because they
417are new; place new input-only parameters before the
418output parameters.</p>
419
420<p>This is not a hard-and-fast rule. Parameters that are
421both input and output (often classes/structs) muddy the
422waters, and, as always, consistency with related
423functions 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
431dependencies: 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>
437All of a project's header files should be
438listed as descendants of the project's source
439directory 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>
444should 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
451purpose is to implement or test the stuff in
452<code><var>dir2/foo2</var>.h</code>, order your includes
453as 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
472includes, the build of <code><var>dir/foo</var>.cc</code>
473or <code><var>dir/foo</var>_test.cc</code> will break.
474Thus, this rule ensures that build breaks show up first
475for the people working on these files, not for innocent
476people 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
480directory (e.g. <code>base/basictypes_test.cc</code> and
481<code>base/basictypes.h</code>), but may sometimes be in different
482directories too.</p>
483
484
485
486<p>Within each section the includes should be ordered
487alphabetically. Note that older code might not conform to
488this rule and should be fixed when convenient.</p>
489
490<p>You should include all the headers that define the symbols you rely
491upon (except in cases of <a href="#Forward_Declarations">forward
492declaration</a>). If you rely on symbols from <code>bar.h</code>,
493don'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>
495yourself, unless <code>foo.h</code> explicitly demonstrates its intent
496to provide you the symbols of <code>bar.h</code>. However, any
497includes present in the related header do not need to be included
498again in the related <code>cc</code> (i.e., <code>foo.cc</code> can
499rely 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>
504might look like this:</p>
505
506
507<pre>#include "foo/server/fooserver.h"
508
509#include &lt;sys/types.h&gt;
510#include &lt;unistd.h&gt;
511#include &lt;hash_map&gt;
512#include &lt;vector&gt;
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
520conditional includes. Such code can put conditional
521includes after other includes. Of course, keep your
522system-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 &lt;initializer_list&gt;
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
538naming. The style of a name immediately informs us what sort of
539thing the named entity is: a type, a variable, a function, a
540constant, a macro, etc., without requiring us to search for the
541declaration of that entity. The pattern-matching engine in our
542brains relies a great deal on these naming rules.
543</p>
544
545<p>Naming rules are pretty arbitrary, but
546 we feel that
547consistency is more important than individual preferences in this
548area, so regardless of whether you find them sensible or not,
549the 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
555descriptive; eschew abbreviation.</p>
556</div>
557
558<div class="stylebody">
559<p>Give as descriptive a name as possible, within reason.
560Do not worry about saving horizontal space as it is far
561more important to make your code immediately
562understandable by a new reader. Do not use abbreviations
563that are ambiguous or unfamiliar to readers outside your
564project, and do not abbreviate by deleting letters within
565a word.</p>
566
567<pre>int price_count_reader; // No abbreviation.
568int num_errors; // "num" is a widespread convention.
569int num_dns_connections; // Most people know what "DNS" stands for.
570</pre>
571
572<pre class="badcode">int n; // Meaningless.
573int nerr; // Ambiguous abbreviation.
574int n_comp_conns; // Ambiguous abbreviation.
575int wgc_connections; // Only your group knows what this stands for.
576int pc_reader; // Lots of things can be abbreviated "pc".
577int 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
586underscores (<code>_</code>) or dashes (<code>-</code>).
587Follow the convention that your
588
589project uses. If there is no consistent
590local 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
606should 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
613example, use <code>http_server_logs.h</code> rather than
614<code>logs.h</code>. A very common case is to have a pair
615of 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
620your inline functions are very short, they should go
621directly 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
629letter 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 &#8212; classes, structs, typedefs,
636and enums &#8212; have the same naming convention. Type names
637should start with a capital letter and have a capital letter
638for each new word. No underscores. For example:</p>
639
640<pre>// classes and structs
641class UrlTable { ...
642class UrlTableTester { ...
643struct UrlTableProperties { ...
644
645// typedefs
646typedef hash_map&lt;UrlTableProperties *, string&gt; PropertiesMap;
647
648// enums
649enum 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
658underscores between words. Data members of classes (but not structs)
659additionally 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.
671string 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
680named 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&lt;TableInfo&gt;* 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,
695are named like ordinary nonmember variables. They do not have
696the preceding "m_" that data members in classes have.</p>
697
698<pre>struct UrlTableProperties {
699 string name;
700 int num_entries;
701 static Pool&lt;UrlTableProperties&gt;* pool;
702};
703</pre>
704
705
706<p>See <a href="#Structs_vs._Classes">Structs vs.
707Classes</a> for a discussion of when to use a struct
708versus a class.</p>
709
710<h4 class="stylepoint_subsection">Global Variables</h4>
711
712<p>There are no special requirements for global
713variables, which should be rare in any case, but if you
714use one, consider prefixing it with <code>g_</code> or
715some other marker to easily distinguish it from local
716variables.</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
730follow a different naming convention from other variables.
731Use 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;
737otherwise 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
745match 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
757a capital letter for each new word. No underscores.</p>
758
759<p>If your function crashes upon an error, you should
760append OrDie to the function name. This only applies to
761functions which could be used by production code and to
762errors that are reasonably likely to occur during normal
763operation.</p>
764
765 <pre>AddTableEntry()
766DeleteUrl()
767OpenFileOrDie()
768</pre>
769
770<h4 class="stylepoint_subsection">Accessors and Mutators</h4>
771
772<p>Accessors and mutators (get and set functions) should
773match the name of the variable they are getting and
774setting. This shows an excerpt of a class whose instance
775variable 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
789short inlined functions. For example if a function were
790so cheap you would not cache the value if you were
791calling it in a loop, then lowercase naming would be
792acceptable.</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,
802and based on project names and possibly their directory
803structure: <code>google_awesome_project</code>.</p>
804</div>
805
806<div class="stylebody">
807
808<p>See <a href="#Namespaces">Namespaces</a> for a
809discussion 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
825like <a href="#Constant_Names">constants</a>. However, it
826is 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
830therefore mixed case.</p>
831
832<pre>enum UrlTableErrors {
833 kOK = 0,
834 kErrorOutOfMemory,
835 kErrorMalformedInput,
836};
837enum 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
845like <a href="#Macro_Names">macros</a>. This caused
846problems with name collisions between enum values and
847macros. Hence, the change to prefer constant-style naming
848was put in place. New code should prefer constant-style
849naming if possible. However, there is no reason to change
850old code to use constant-style names, unless the old
851names 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">
861define 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
868of macros</a>; in general macros should <em>not</em> be used.
869However, if they are absolutely needed, then they should be
870named 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
882existing C or C++ entity then you can follow the existing
883naming 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
911keeping our code readable. The following rules describe what
912you should comment and where. But remember: while comments are
913very important, the best code is self-documenting. Giving
914sensible names to types and variables is much better than using
915obscure names that you must then explain through comments.</p>
916
917<p>When writing your comments, write for your audience: the
918next
919contributor who will need to
920understand your code. Be generous &#8212; the next
921one 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>
927syntax, 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
935comment 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
943boilerplate, followed by a description of its
944contents.</p>
945</div>
946
947<div class="stylebody">
948
949<h4 class="stylepoint_subsection">Legal Notice and Author
950Line</h4>
951
952
953
954<p>Every file should contain license
955boilerplate. Choose the appropriate boilerplate for the
956license used by the project (for example, Apache 2.0,
957BSD, LGPL, GPL).</p>
958
959<p>If you make significant changes to a file with an
960author 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
965its contents.</p>
966
967<p>Generally a <code>.h</code> file will describe the
968classes that are declared in the file with an overview of
969what they are for and how they are used. A
970<code>.cc</code> file should contain more information
971about implementation details or discussions of tricky
972algorithms. If you feel the implementation details or a
973discussion of the algorithms would be useful for someone
974reading the <code>.h</code>, feel free to put it there
975instead, but mention in the <code>.cc</code> that the
976documentation is in the <code>.h</code> file.</p>
977
978<p>Do not duplicate comments in both the <code>.h</code>
979and the <code>.cc</code>. Duplicated comments
980diverge.</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
988that 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-&gt;NewIterator();
995// for (iter-&gt;Seek("foo"); !iter-&gt;done(); iter-&gt;Next()) {
996// process(iter-&gt;key(), iter-&gt;value());
997// }
998// delete iter;
999class GargantuanTableIterator {
1000 ...
1001};
1002</pre>
1003
1004<p>If you have already described a class in detail in the
1005comments at the top of your file feel free to simply
1006state "See comment at top of file for a complete
1007description", but be sure to have some sort of
1008comment.</p>
1009
1010<p>Document the synchronization assumptions the class
1011makes, if any. If an instance of the class can be
1012accessed by multiple threads, take extra care to document
1013the rules and invariants surrounding multithreaded
1014use.</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
1022at 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
1030immediately preceding it that describe what the function
1031does and how to use it. These comments should be
1032descriptive ("Opens the file") rather than imperative
1033("Open the file"); the comment describes the function, it
1034does not tell the function what to do. In general, these
1035comments do not describe how the function performs its
1036task. Instead, that should be left to comments in the
1037function definition.</p>
1038
1039<p>Types of things to mention in comments at the function
1040declaration:</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-&gt;NewIterator();
1074// iter-&gt;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.
1079Iterator* GetIterator() const;
1080</pre>
1081
1082<p>However, do not be unnecessarily verbose or state the
1083completely obvious. Notice below that it is not necessary
1084 to say "returns false otherwise" because this is
1085implied.</p>
1086
1087<pre>// Returns true if the table cannot hold any more entries.
1088bool IsTableFull();
1089</pre>
1090
1091<p>When commenting constructors and destructors, remember
1092that the person reading your code knows what constructors
1093and destructors are for, so comments that just say
1094something like "destroys this object" are not useful.
1095Document what constructors do with their arguments (for
1096example, if they take ownership of pointers), and what
1097cleanup the destructor does. If this is trivial, just
1098skip the comment. It is quite common for destructors not
1099to 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
1104its job, the function definition should have an
1105explanatory comment. For example, in the definition
1106comment you might describe any coding tricks you use,
1107give an overview of the steps you go through, or explain
1108why you chose to implement the function in the way you
1109did rather than using a viable alternative. For instance,
1110you might mention why it must acquire a lock for the
1111first half of the function but why it is not needed for
1112the second half.</p>
1113
1114<p>Note you should <em>not</em> just repeat the comments
1115given with the function declaration, in the
1116<code>.h</code> file or wherever. It's okay to
1117recapitulate briefly what the function does, but the
1118focus 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
1126descriptive enough to give a good idea of what the variable
1127is 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
1135variable or member variable) should have a comment
1136describing what it is used for. If the variable can take
1137sentinel values with special meanings, such as a null
1138pointer 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
1151a comment describing what they are and what they are used
1152for. For example:</p>
1153
1154<pre>// The total number of tests cases that we run through in this regression test.
1155const 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,
1164non-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
1172before them. Example:</p>
1173
1174<pre>// Divide result by two, taking into account that x
1175// contains the carry from the add.
1176for (int i = 0; i &lt; result-&gt;size(); i++) {
1177 x = (x &lt;&lt; 8) + (*result)[i];
1178 (*result)[i] = x &gt;&gt; 1;
1179 x &amp;= 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
1186at the end of the line. These end-of-line comments should
1187be separated from the code by 2 spaces. Example:</p>
1188
1189<pre>// If we have enough memory, mmap the data portion too.
1190mmap_budget = max&lt;int64&gt;(0, mmap_budget - index_-&gt;length());
1191if (mmap_budget &gt;= data_size_ &amp;&amp; !MmapData(mmap_chunk_bytes, mlock))
1192 return; // Error already logged.
1193</pre>
1194
1195<p>Note that there are both comments that describe what
1196the code is doing, and comments that mention that an
1197error has already been logged when the function
1198returns.</p>
1199
1200<p>If you have several comments on subsequent lines, it
1201can often be more readable to line them up:</p>
1202
1203<pre>DoSomething(); // Comment here so the comments line up.
1204DoSomethingElseThatIsLonger(); // 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}
1209vector&lt;string&gt; list{// Comments in braced lists describe the next element ..
1210 "First item",
1211 // .. and should be aligned appropriately.
1212 "Second item"};
1213DoSomething(); /* 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
1219integer values to functions, you should consider adding a
1220comment about what they are, or make your code
1221self-documenting by using constants. For example,
1222compare:</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;
1241const bool kFirstTimeCalling = false;
1242Callback *null_callback = NULL;
1243bool 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
1252itself. Assume that the person reading the code knows C++
1253better than you do, even though he or she does not know
1254what 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
1267easier to read well-written comments than badly written
1268ones.</p>
1269</div>
1270
1271<div class="stylebody">
1272
1273<p>Comments should be as readable as narrative text, with
1274proper capitalization and punctuation. In many cases,
1275complete sentences are more readable than sentence
1276fragments. Shorter comments, such as comments at the end
1277of a line of code, can sometimes be less formal, but you
1278should be consistent with your style.</p>
1279
1280<p>Although it can be frustrating to have a code reviewer
1281point out that you are using a comma when you should be
1282using a semicolon, it is very important that source code
1283maintain a high level of clarity and readability. Proper
1284punctuation, spelling, and grammar help with that
1285goal.</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,
1293a 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
1301name, e-mail address, or other
1302identifier of the person
1303 with the best context
1304about the problem referenced by the <code>TODO</code>. The
1305main purpose is to have a consistent <code>TODO</code> that
1306can be searched to find out how to get more details upon
1307request. A <code>TODO</code> is not a commitment that the
1308person referenced will fix the problem. Thus when you create
1309a <code>TODO</code>, it is almost always your
1310
1311name
1312that 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
1323date do something" make sure that you either include a
1324very specific date ("Fix by November 2005") or a very
1325specific event ("Remove this code when all clients can
1326handle 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>
1334comments.</p>
1335</div>
1336
1337<div class="stylebody">
1338
1339<p>You can mark an interface as deprecated by writing a
1340comment containing the word <code>DEPRECATED</code> in
1341all caps. The comment goes either before the declaration
1342of the interface or on the same line as the
1343declaration.</p>
1344
1345
1346
1347<p>After the word
1348<code>DEPRECATED</code>, write your name, e-mail address,
1349or other identifier in parentheses.</p>
1350
1351<p>A deprecation comment must include simple, clear
1352directions for people to fix their callsites. In C++, you
1353can implement a deprecated function as an inline function
1354that calls the new interface point.</p>
1355
1356<p>Marking an interface point <code>DEPRECATED</code>
1357will not magically cause any callsites to change. If you
1358want people to actually stop using the deprecated
1359facility, you will have to fix the callsites yourself or
1360recruit a crew to help you.</p>
1361
1362<p>New code should not contain calls to deprecated
1363interface points. Use the new interface point instead. If
1364you cannot understand the directions, find the person who
1365created the deprecation and ask them for help using the
1366new 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
1376project is much easier to follow
1377if everyone uses the same style. Individuals may not agree with every
1378aspect of the formatting rules, and some of the rules may take
1379some getting used to, but it is important that all
1380
1381project contributors follow the
1382style rules so that
1383they can all read and understand
1384everyone's code easily.</p>
1385
1386
1387
1388<p>To help you format code correctly, we've
1389created a
1390<a href="http://google-styleguide.googlecode.com/svn/trunk/google-c-style.el">
1391settings 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
1397characters long.</p>
1398</div>
1399
1400<div class="stylebody">
1401
1402
1403
1404 <p>We recognize that this rule is
1405controversial, but so much existing code already adheres
1406to it, and we feel that consistency is important.</p>
1407
1408<div class="pros">
1409<p>Those who favor this rule
1410argue that it is rude to force them to resize
1411their windows and there is no need for anything longer.
1412Some folks are used to having several code windows
1413side-by-side, and thus don't have room to widen their
1414windows in any case. People set up their work environment
1415assuming a particular maximum window width, and 80
1416columns has been the traditional standard. Why change
1417it?</p>
1418</div>
1419
1420<div class="cons">
1421<p>Proponents of change argue that a wider line can make
1422code more readable. The 80-column limit is an hidebound
1423throwback to 1960s mainframes; modern equipment has wide screens that
1424can 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
1431command or a literal URL longer than 80 characters, that
1432line may be longer than 80 characters for ease of cut and
1433paste.</p>
1434
1435<p class="exception">A raw-string literal may have content
1436that exceeds 80 characters. Except for test code, such literals
1437should appear near top of a file.</p>
1438
1439<p class="exception">An <code>#include</code> statement with a
1440long 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
1444the 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
1453formatting.</p>
1454</div>
1455
1456<div class="stylebody">
1457
1458<p>You shouldn't hard-code user-facing text in source,
1459even English, so use of non-ASCII characters should be
1460rare. However, in certain cases it is appropriate to
1461include such words in your code. For example, if your
1462code parses data files from foreign sources, it may be
1463appropriate to hard-code the non-ASCII string(s) used in
1464those data files as delimiters. More commonly, unittest
1465code (which does not need to be localized) might
1466contain non-ASCII strings. In such cases, you should use
1467UTF-8, since that is an encoding
1468understood by most tools able to handle more than just
1469ASCII.</p>
1470
1471<p>Hex encoding is also OK, and encouraged where it
1472enhances readability &#8212; for example,
1473<code>"\xEF\xBB\xBF"</code>, or, even more simply,
1474<code>u8"\uFEFF"</code>, is the Unicode zero-width
1475no-break space character, which would be invisible if
1476included in the source as straight UTF-8.</p>
1477
1478<p>Use the <code>u8</code> prefix
1479to guarantee that a string literal containing
1480<code>\uXXXX</code> escape sequences is encoded as UTF-8.
1481Do not use it for strings containing non-ASCII characters
1482encoded as UTF-8, because that will produce incorrect
1483output if the compiler does not interpret the source file
1484as 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
1488non-UTF-8 text. For similar reasons you also shouldn't
1489use <code>wchar_t</code> (unless you're writing code that
1490interacts 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
1504code. You should set your editor to emit spaces when you
1505hit 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
1513on the same line if they fit. Wrap parameter lists which do
1514not fit on a single line as you would wrap arguments in a
1515function 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
1588variable name in the function definition:</p>
1589
1590<pre>// Always have named parameters in interfaces.
1591class Shape {
1592 public:
1593 virtual void Rotate(double radians) = 0;
1594};
1595
1596// Always have named parameters in the declaration.
1597class Circle : public Shape {
1598 public:
1599 virtual void Rotate(double radians);
1600};
1601
1602// Comment out unused named parameters in definitions.
1603void 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.
1608void 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
1617lists 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
1622ampersand (&amp;) and the variable name.</p>
1623<pre>int x = 0;
1624auto add_to_x = [&amp;x](int n) { x += n; };
1625</pre>
1626<p>Short lambdas may be written inline as function arguments.</p>
1627<pre>std::set&lt;int&gt; blacklist = {7, 8, 9};
1628std::vector&lt;int&gt; digits = {3, 9, 1, 8, 4, 7, 1};
1629digits.erase(std::remove_if(digits.begin(), digits.end(), [&amp;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
1641arguments at the parenthesis, or start the arguments on a new
1642line indented by four spaces and continue at that 4 space
1643indent. In the absence of other considerations, use the
1644minimum number of lines, including placing multiple arguments
1645on 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
1655should be broken up onto multiple lines, with each
1656subsequent line aligned with the first argument. Do not
1657add spaces after the open paren or before the close
1658paren:</p>
1659<pre>bool retval = DoSomething(averyveryveryverylongargument1,
1660 argument2, argument3);
1661</pre>
1662
1663<p>Arguments may optionally all be placed on subsequent
1664lines 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
1676number of lines necessary for calling a function unless
1677there is a specific readability problem. Some find that
1678formatting with strictly one argument on each line is
1679more readable and simplifies editing of the arguments.
1680However, we prioritize for the reader over the ease of
1681editing arguments, and most readability problems are
1682better addressed with the following techniques.</p>
1683
1684<p>If having multiple arguments in a single line decreases
1685readability due to the complexity or confusing nature of the
1686expressions that make up some arguments, try creating
1687variables that capture those arguments in a descriptive name:</p>
1688<pre>int my_heuristic = scores[x] * y + bases[x];
1689bool retval = DoSomething(my_heuristic, x, y, z);
1690</pre>
1691
1692<p>Or put the confusing argument on its own line with
1693an 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
1699significantly more readable on its own line, then put it on
1700its own line. The decision should be specific to the argument
1701which is made more readable rather than a general policy.</p>
1702
1703<p>Sometimes arguments form a structure that is important
1704for readability. In those cases, feel free to format the
1705arguments according to that structure:</p>
1706<pre>// Transform the widget by a 3x3 matrix.
1707my_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>
1718exactly 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
1724variable name), format as if the <code>{}</code> were the
1725parentheses of a function call with that name. If there
1726is no name, assume a zero-length name.</p>
1727
1728<pre>// Examples of braced init list on a single line.
1729return {foo, bar};
1730functioncall({foo, bar});
1731pair&lt;int, int&gt; p{foo, bar};
1732
1733// When you have to wrap.
1734SomeFunction(
1735 {"assume a zero-length name before {"},
1736 some_other_function_parameter);
1737SomeType 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}};
1745SomeType variable{
1746 "This is too long to fit all in one line"};
1747MyType 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>
1761and <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
1767conditional statement. One includes spaces between the
1768parentheses and the condition, and one does not.</p>
1769
1770<p>The most common form is without spaces. Either is
1771fine, but <em>be consistent</em>. If you are modifying a
1772file, use the format that is already present. If you are
1773writing new code, use the format that the other files in
1774that directory or project use. If in doubt and you have
1775no 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
1787parentheses:</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
1797the <code>if</code> and the open parenthesis. You must
1798also have a space between the close parenthesis and the
1799curly brace, if you're using one.</p>
1800
1801<pre class="badcode">if(condition) { // Bad - space missing after IF.
1802if (condition){ // Bad - space missing before {.
1803if(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
1810line if this enhances readability. You may use this only
1811when 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();
1815if (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
1822if (x) DoThis();
1823else DoThat();
1824</pre>
1825
1826<p>In general, curly braces are not required for
1827single-line statements, but they are allowed if you like
1828them; conditional or loop statements with complex
1829conditions or statements may be more readable with curly
1830braces. Some
1831projects require that an
1832<code>if</code> must always always have an accompanying
1833brace.</p>
1834
1835<pre>if (condition)
1836 DoSomething(); // 2 space indent.
1837
1838if (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
1845braces, the other part must too:</p>
1846
1847<pre class="badcode">// Not allowed - curly on IF but not ELSE
1848if (condition) {
1849 foo;
1850} else
1851 bar;
1852
1853// Not allowed - curly on ELSE but not IF
1854if (condition)
1855 foo;
1856else {
1857 bar;
1858}
1859</pre>
1860
1861<pre>// Curly braces around both IF and ELSE required because
1862// one of the clauses used braces.
1863if (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
1876non-trivial fall-through between cases.
1877Braces are optional for single-statement loops.
1878Empty 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>
1884statements can have curly braces or not, depending on
1885your preference. If you do include curly braces they
1886should be placed as shown below.</p>
1887
1888<p>If not conditional on an enumerated value, switch
1889statements should always have a <code>default</code> case
1890(in the case of an enumerated value, the compiler will
1891warn you if any values are not handled). If the default
1892case 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 &lt; kSomeNumber; ++i)
1921 printf("I love you\n");
1922
1923for (int i = 0; i &lt; 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}
1935for (int i = 0; i &lt; kSomeNumber; ++i) {} // Good - empty body.
1936while (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
1948have trailing spaces.</p>
1949</div>
1950
1951<div class="stylebody">
1952
1953<p>The following are examples of correctly-formatted
1954pointer and reference expressions:</p>
1955
1956<pre>x = *p;
1957p = &amp;x;
1958x = r.y;
1959x = r-&gt;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>&amp;</code>.</li>
1970</ul>
1971
1972<p>When declaring a pointer variable or argument, you may
1973place the asterisk adjacent to either the type or to the
1974variable name:</p>
1975
1976<pre>// These are fine, space preceding.
1977char *c;
1978const string &amp;str;
1979
1980// These are fine, space following.
1981char* c; // but remember to do "char* c, *d, *e, ...;"!
1982const string&amp; str;
1983</pre>
1984
1985<pre class="badcode">char * c; // Bad - spaces on both sides of *
1986const string &amp; str; // Bad - spaces on both sides of &amp;
1987</pre>
1988
1989<p>You should do this consistently within a single
1990file,
1991so, when modifying an existing file, use the style in
1992that 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
2001consistent 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
2007the end of the lines:</p>
2008
2009<pre>if (this_one_thing &gt; this_other_thing &amp;&amp;
2010 a_third_thing == a_fourth_thing &amp;&amp;
2011 yet_another &amp;&amp; last_one) {
2012 ...
2013}
2014</pre>
2015
2016<p>Note that when the code wraps in this example, both of
2017the <code>&amp;&amp;</code> logical AND operators are at
2018the end of the line. This is more common in Google code,
2019though wrapping all operators at the beginning of the
2020line is also allowed. Feel free to insert extra
2021parentheses judiciously because they can be very helpful
2022in increasing readability when used
2023appropriately. Also note that you should always use
2024the punctuation operators, such as
2025<code>&amp;&amp;</code> and <code>~</code>, rather than
2026the 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>
2035expression with parentheses.</p>
2036</div>
2037
2038<div class="stylebody">
2039
2040<p>Use parentheses in <code>return expr;</code> only
2041where 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.
2045return (some_long_condition &amp;&amp;
2046 another_condition);
2047</pre>
2048
2049<pre class="badcode">return (value); // You wouldn't write var = (value);
2050return(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
2068all correct:</p>
2069
2070<pre>int x = 3;
2071int x(3);
2072int x{3};
2073string name = "Some Name";
2074string name("Some Name");
2075string name{"Some Name"};
2076</pre>
2077
2078<p>Be careful when using a braced initialization list <code>{...}</code>
2079on a type with an <code>std::initializer_list</code> constructor.
2080A nonempty <i>braced-init-list</i> prefers the
2081<code>std::initializer_list</code> constructor whenever
2082possible. Note that empty braces <code>{}</code> are special, and
2083will call a default constructor if available. To force the
2084non-<code>std::initializer_list</code> constructor, use parentheses
2085instead of braces.</p>
2086
2087<pre>vector&lt;int&gt; v(100, 1); // A vector of 100 1s.
2088vector&lt;int&gt; v{100, 1}; // A vector of 100, 1.
2089</pre>
2090
2091<p>Also, the brace form prevents narrowing of integral
2092types. This can prevent some types of programming
2093errors.</p>
2094
2095<pre>int pi(3.14); // OK -- pi == 3.
2096int 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
2105always 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
2111of indented code, the directives should start at the
2112beginning 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
2147comments, see <a href="#Class_Comments">Class
2148Comments</a> for a discussion of what comments are
2149needed) 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
2204with subsequent lines indented four spaces.</p>
2205</div>
2206
2207<div class="stylebody">
2208
2209<p>There are two acceptable formats for initializer
2210lists:</p>
2211
2212<pre>// When it all fits on one line:
2213MyClass::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:
2220MyClass::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
2240extra level of indentation. For example, use:</p>
2241
2242<pre>namespace {
2243
2244void 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
2264on its own line.</p>
2265
2266<pre>namespace foo {
2267namespace 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
2276trailing 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 ...
2285int 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!
2288int x[] = { 0 };
2289int x[] = {0};
2290
2291// Spaces around the colon in inheritance and initializer lists.
2292class 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
2302others editing the same file, when they merge, as can
2303removing existing trailing whitespace. So: Don't
2304introduce trailing whitespace. Remove it if you're
2305already changing that line, or do it in a separate
2306clean-up
2307operation (preferably when no-one
2308else 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}
2315while (test) {} // There is usually no space inside parentheses.
2316switch (i) {
2317for (int i = 0; i &lt; 5; ++i) {
2318// Loops and conditions may have spaces inside parentheses, but this
2319// is rare. Be consistent.
2320switch ( i ) {
2321if ( test ) {
2322for ( int i = 0; i &lt; 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.
2325for ( ; i &lt; 5 ; ++i) {
2326 ...
2327
2328// Range-based for loops always have a space before and after the colon.
2329for (auto x : counts) {
2330 ...
2331}
2332switch (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.
2341x = 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.
2346v = w * x + y / z;
2347v = w*x + y/z;
2348v = w * (x + z);
2349
2350// No spaces separating unary operators and their arguments.
2351x = -5;
2352++x;
2353if (x &amp;&amp; !y)
2354 ...
2355</pre>
2356
2357<h4 class="stylepoint_subsection">Templates and Casts</h4>
2358
2359<pre>// No spaces inside the angle brackets (&lt; and &gt;), before
2360// &lt;, or between &gt;( in a cast
2361vector&lt;string&gt; x;
2362y = static_cast&lt;char*&gt;(x);
2363
2364// Spaces between type and pointer are OK, but be consistent.
2365vector&lt;char *&gt; x;
2366set&lt;list&lt;string&gt;&gt; x; // Permitted in C++11 code.
2367set&lt;list&lt;string&gt; &gt; x; // C++03 required a space in &gt; &gt;.
2368
2369// You may optionally use symmetric spacing in &lt; &lt;.
2370set&lt; list&lt;string&gt; &gt; 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
2384lines when you don't have to. In particular, don't put
2385more than one or two blank lines between functions,
2386resist starting functions with a blank line, don't end
2387functions with a blank line, and be discriminating with
2388your use of blank lines inside functions.</p>
2389
2390<p>The basic principle is: The more code that fits on one
2391screen, the easier it is to follow and understand the
2392control flow of the program. Of course, readability can
2393suffer from code being too dense as well as too spread
2394out, so use your judgement. But in general, minimize use
2395of vertical whitespace.</p>
2396
2397<p>Some rules of thumb to help when blank lines may be
2398useful:</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.
2413However, like all good rules, these sometimes have exceptions,
2414which 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
2423does 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
2429to specifications other than those presented by this
2430guide, you may have to diverge from these rules in order
2431to stay consistent with the local conventions in that
2432code. If you are in doubt about how to do this, ask the
2433original author or the person currently responsible for
2434the code. Remember that <em>consistency</em> includes
2435local 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
2446code around you and determine its style. If they use spaces
2447around their <code>if</code> clauses, you should, too. If their
2448comments have little boxes of stars around them, make your
2449comments have little boxes of stars around them too.</p>
2450
2451<p>The point of having style guidelines is to have a common
2452vocabulary of coding so people can concentrate on what you are
2453saying, rather than on how you are saying it. We present global
2454style rules here so people know the vocabulary. But local style
2455is also important. If code you add to a file looks drastically
2456different from the existing code around it, the discontinuity
2457throws readers out of their rhythm when they go to read it. Try
2458to avoid this.</p>
2459
2460
2461
2462<p>OK, enough writing about writing code; the code itself is much
2463more 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>