﻿{"id":1522,"date":"2011-03-08T15:57:01","date_gmt":"2011-03-08T07:57:01","guid":{"rendered":"http:\/\/blog.jixin.ntxz.net\/?p=1522"},"modified":"2011-03-08T15:57:01","modified_gmt":"2011-03-08T07:57:01","slug":"google-c-style-guide","status":"publish","type":"post","link":"http:\/\/www.ntxz.net\/?p=1522","title":{"rendered":"Google C++ Style Guide"},"content":{"rendered":"<p>\u00a0<\/p>\n<div class=\"toc\">\n<div class=\"toc_title\">Table of Contents<\/div>\n<table>\n<tbody>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Header_Files\">Header Files<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#The__define_Guard\">The #define Guard<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Header_File_Dependencies\">Header File Dependencies<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Inline_Functions\">Inline Functions<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#The_-inl.h_Files\">The -inl.h Files<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Parameter_Ordering\">Function Parameter Ordering<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Names_and_Order_of_Includes\">Names and Order of Includes<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Scoping\">Scoping<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespaces\">Namespaces<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Nested_Classes\">Nested Classes<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Nonmember,_Static_Member,_and_Global_Functions\">Nonmember, Static Member, and Global Functions<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Local_Variables\">Local Variables<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Static_and_Global_Variables\">Static and Global Variables<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Classes\">Classes<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Doing_Work_in_Constructors\">Doing Work in Constructors<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Default_Constructors\">Default Constructors<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Explicit_Constructors\">Explicit Constructors<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Copy_Constructors\">Copy Constructors<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Structs_vs._Classes\">Structs vs. Classes<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Inheritance\">Inheritance<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Multiple_Inheritance\">Multiple Inheritance<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Interfaces\">Interfaces<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Operator_Overloading\">Operator Overloading<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Access_Control\">Access Control<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Declaration_Order\">Declaration Order<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Write_Short_Functions\">Write Short Functions<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Google-Specific_Magic\">Google-Specific Magic<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Smart_Pointers\">Smart Pointers<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#cpplint\">cpplint<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Other_C++_Features\">Other C++ Features<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Reference_Arguments\">Reference Arguments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Overloading\">Function Overloading<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Default_Arguments\">Default Arguments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Variable-Length_Arrays_and_alloca__\">Variable-Length Arrays and alloca()<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Friends\">Friends<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Exceptions\">Exceptions<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Run-Time_Type_Information__RTTI_\">Run-Time Type Information (RTTI)<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Casting\">Casting<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Streams\">Streams<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Preincrement_and_Predecrement\">Preincrement and Predecrement<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Use_of_const\">Use of const<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Integer_Types\">Integer Types<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#64-bit_Portability\">64-bit Portability<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Preprocessor_Macros\">Preprocessor Macros<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#0_and_NULL\">0 and NULL<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#sizeof\">sizeof<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Boost\">Boost<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#C++0x\">C++0x<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Naming\">Naming<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#General_Naming_Rules\">General Naming Rules<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#File_Names\">File Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Type_Names\">Type Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Variable_Names\">Variable Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Constant_Names\">Constant Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Names\">Function Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespace_Names\">Namespace Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Enumerator_Names\">Enumerator Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Macro_Names\">Macro Names<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Exceptions_to_Naming_Rules\">Exceptions to Naming Rules<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Comments\">Comments<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Comment_Style\">Comment Style<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#File_Comments\">File Comments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Class_Comments\">Class Comments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Comments\">Function Comments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Variable_Comments\">Variable Comments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Implementation_Comments\">Implementation Comments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Punctuation,_Spelling_and_Grammar\">Punctuation, Spelling and Grammar<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#TODO_Comments\">TODO Comments<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Deprecation_Comments\">Deprecation Comments<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Formatting\">Formatting<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Line_Length\">Line Length<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Non-ASCII_Characters\">Non-ASCII Characters<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Spaces_vs._Tabs\">Spaces vs. Tabs<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Declarations_and_Definitions\">Function Declarations and Definitions<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Calls\">Function Calls<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Conditionals\">Conditionals<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Loops_and_Switch_Statements\">Loops and Switch Statements<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Pointer_and_Reference_Expressions\">Pointer and Reference Expressions<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Boolean_Expressions\">Boolean Expressions<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Return_Values\">Return Values<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Variable_and_Array_Initialization\">Variable and Array Initialization<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Preprocessor_Directives\">Preprocessor Directives<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Class_Format\">Class Format<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Constructor_Initializer_Lists\">Constructor Initializer Lists<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespace_Formatting\">Namespace Formatting<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Horizontal_Whitespace\">Horizontal Whitespace<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Vertical_Whitespace\">Vertical Whitespace<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<tr valign=\"top\">\n<td>\n<div class=\"toc_category\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Exceptions_to_the_Rules\">Exceptions to the Rules<\/a><\/div>\n<\/td>\n<td>\n<div class=\"toc_stylepoint\"><span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Existing_Non-conformant_Code\">Existing Non-conformant Code<\/a><\/span> <span style=\"padding-right: 1em; white-space: nowrap;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Windows_Code\">Windows Code<\/a><\/span><\/div>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<div>\n<h2 id=\"Important_Note\">Important Note<\/h2>\n<div>\n<h3><a id=\"Displaying_Hidden_Details_in_this_Guide\" name=\"Displaying_Hidden_Details_in_this_Guide\">Displaying Hidden Details in this Guide<\/a><\/h3>\n<p><span id=\"link-Displaying_Hidden_Details_in_this_Guide__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Displaying_Hidden_Details_in_this_Guide#Displaying_Hidden_Details_in_this_Guide\">link <\/a><\/span><span id=\"Displaying_Hidden_Details_in_this_Guide__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Displaying_Hidden_Details_in_this_Guide__body','Displaying_Hidden_Details_in_this_Guide__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see &#8220;Hooray&#8221; appear below.<\/div>\n<div>\n<div id=\"Displaying_Hidden_Details_in_this_Guide__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>Hooray! Now you know you can expand points to get more details. Alternatively, there&#8217;s an &#8220;expand all&#8221; at the top of this document.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Background\">Background<\/h2>\n<p>C++ is the main development language used by many of Google&#8217;s open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain.<\/p>\n<p>The goal of this guide is to manage this complexity by describing in detail the dos and don&#8217;ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively.<\/p>\n<p><em>Style<\/em>, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting.<\/p>\n<p>One way in which we keep the code base manageable is by enforcing <em>consistency<\/em>. It is very important that any programmer be able to look at another&#8217;s code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use &#8220;pattern-matching&#8221; to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency.<\/p>\n<p>Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted.<\/p>\n<p>Open-source projects developed by Google conform to the requirements in this guide.<\/p>\n<p>Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language.<\/p>\n<\/div>\n<div>\n<h2 id=\"Header_Files\">Header Files<\/h2>\n<p>In general, every <code>.cc<\/code> file should have an associated <code>.h<\/code> file. There are some common exceptions, such as unittests and small <code>.cc<\/code> files containing just a <code>main()<\/code> function.<\/p>\n<p>Correct use of header files can make a huge difference to the readability, size and performance of your code.<\/p>\n<p>The following rules will guide you through the various pitfalls of using header files.<\/p>\n<div>\n<h3><a id=\"The__define_Guard\" name=\"The__define_Guard\">The #define Guard<\/a><\/h3>\n<p><span id=\"link-The__define_Guard__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=The__define_Guard#The__define_Guard\">link <\/a><\/span><span id=\"The__define_Guard__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('The__define_Guard__body','The__define_Guard__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">All header files should have <code>#define<\/code> guards to prevent multiple inclusion. The format of the symbol name should be <code><em>&lt;PROJECT&gt;<\/em>_<em>&lt;PATH&gt;<\/em>_<em>&lt;FILE&gt;<\/em>_H_<\/code>.<\/div>\n<div>\n<div id=\"The__define_Guard__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>To guarantee uniqueness, they should be based on the full path in a project&#8217;s source tree. For example, the file <code>foo\/src\/bar\/baz.h<\/code> in project <code>foo<\/code> should have the following guard:<\/p>\n<div>\n<pre>#ifndef FOO_BAR_BAZ_H_\r\n#define FOO_BAR_BAZ_H_\r\n\r\n...\r\n\r\n#endif  \/\/ FOO_BAR_BAZ_H_<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Header_File_Dependencies\" name=\"Header_File_Dependencies\">Header File Dependencies<\/a><\/h3>\n<p><span id=\"link-Header_File_Dependencies__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Header_File_Dependencies#Header_File_Dependencies\">link <\/a><\/span><span id=\"Header_File_Dependencies__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Header_File_Dependencies__body','Header_File_Dependencies__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Don&#8217;t use an <code>#include<\/code> when a forward declaration would suffice.<\/div>\n<div>\n<div id=\"Header_File_Dependencies__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files.<\/p>\n<p>You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the <code>File<\/code> class in ways that do not require access to the declaration of the <code>File<\/code> class, your header file can just forward declare <code>class File;<\/code> instead of having to <code>#include \"file\/base\/file.h\"<\/code>.<\/p>\n<p>How can we use a class <code>Foo<\/code> in a header file without access to its definition?<\/p>\n<ul>\n<li>We can declare data members of type <code>Foo*<\/code> or <code>Foo&amp;<\/code>.<\/li>\n<li>We can declare (but not define) functions with arguments, and\/or return values, of type <code>Foo<\/code>. (One exception is if an argument <code>Foo<\/code> or <code>const Foo&amp;<\/code> has a non-<code>explicit<\/code>, one-argument constructor, in which case we need the full definition to support automatic type conversion.)<\/li>\n<li>We can declare static data members of type <code>Foo<\/code>. This is because static data members are defined outside the class definition.<\/li>\n<\/ul>\n<p>On the other hand, you must include the header file for <code>Foo<\/code> if your class subclasses <code>Foo<\/code> or has a data member of type <code>Foo<\/code>.<\/p>\n<p>Sometimes it makes sense to have pointer (or better, <code>scoped_ptr<\/code>) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files.<\/p>\n<p>Of course, <code>.cc<\/code> files typically do require the definitions of the classes they use, and usually have to include several header files.<\/p>\n<p><span class=\"stylepoint_subsection\">Note:<\/span> If you use a symbol <code>Foo<\/code> in your source file, you should bring in a definition for <code>Foo<\/code> yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if <code>Foo<\/code> is used in <code>myfile.cc<\/code>, it&#8217;s ok to #include (or forward-declare) <code>Foo<\/code> in <code>myfile.h<\/code>, instead of <code>myfile.cc<\/code>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Inline_Functions\" name=\"Inline_Functions\">Inline Functions<\/a><\/h3>\n<p><span id=\"link-Inline_Functions__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Inline_Functions#Inline_Functions\">link <\/a><\/span><span id=\"Inline_Functions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Inline_Functions__body','Inline_Functions__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Define functions inline only when they are small, say, 10 lines or less.<\/div>\n<div>\n<div id=\"Inline_Functions__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Overuse of inlining can actually make programs slower. Depending on a function&#8217;s size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls!<\/p>\n<p>Another useful rule of thumb: it&#8217;s typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed).<\/p>\n<p>It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"The_-inl.h_Files\" name=\"The_-inl.h_Files\">The -inl.h Files<\/a><\/h3>\n<p><span id=\"link-The_-inl.h_Files__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=The_-inl.h_Files#The_-inl.h_Files\">link <\/a><\/span><span id=\"The_-inl.h_Files__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('The_-inl.h_Files__body','The_-inl.h_Files__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">You may use file names with a <code>-inl.h<\/code> suffix to define complex inline functions when needed.<\/div>\n<div>\n<div id=\"The_-inl.h_Files__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in <code>.cc<\/code> files, and we do not like to have much actual code in <code>.h<\/code> files unless there is a readability or performance advantage.<\/p>\n<p>If an inline function definition is short, with very little, if any, logic in it, you should put the code in your <code>.h<\/code> file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a <code>.h<\/code> file for the convenience of the implementer and callers, though if this makes the <code>.h<\/code> file too unwieldy you can instead put that code in a separate <code>-inl.h<\/code> file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary.<\/p>\n<p>Another use of <code>-inl.h<\/code> files is for definitions of function templates. This can be used to keep your template definitions easy to read.<\/p>\n<p>Do not forget that a <code>-inl.h<\/code> file requires a <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#The__define_Guard\"><code>#define<\/code> guard<\/a> just like any other header file.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Function_Parameter_Ordering\" name=\"Function_Parameter_Ordering\">Function Parameter Ordering<\/a><\/h3>\n<p><span id=\"link-Function_Parameter_Ordering__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Function_Parameter_Ordering#Function_Parameter_Ordering\">link <\/a><\/span><span id=\"Function_Parameter_Ordering__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Function_Parameter_Ordering__body','Function_Parameter_Ordering__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">When defining a function, parameter order is: inputs, then outputs.<\/div>\n<div>\n<div id=\"Function_Parameter_Ordering__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>Parameters to C\/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or <code>const<\/code> references, while output and input\/output parameters will be non-<code>const<\/code> pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters.<\/p>\n<p>This is not a hard-and-fast rule. Parameters that are both input and output (often classes\/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Names_and_Order_of_Includes\" name=\"Names_and_Order_of_Includes\">Names and Order of Includes<\/a><\/h3>\n<p><span id=\"link-Names_and_Order_of_Includes__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Names_and_Order_of_Includes#Names_and_Order_of_Includes\">link <\/a><\/span><span id=\"Names_and_Order_of_Includes__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Names_and_Order_of_Includes__body','Names_and_Order_of_Includes__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries&#8217; <code>.h<\/code>, your project&#8217;s <code>.h<\/code>.<\/div>\n<div>\n<div id=\"Names_and_Order_of_Includes__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>All of a project&#8217;s header files should be listed as descentants of the project&#8217;s source directory without use of UNIX directory shortcuts <code>.<\/code> (the current directory) or <code>..<\/code> (the parent directory). For example, <code>google-awesome-project\/src\/base\/logging.h<\/code> should be included as<\/p>\n<div>\n<pre>#include \"base\/logging.h\"<\/pre>\n<\/div>\n<p>In <code><var>dir\/foo<\/var>.cc<\/code>, whose main purpose is to implement or test the stuff in <code><var>dir2\/foo2<\/var>.h<\/code>, order your includes as follows:<\/p>\n<ol>\n<li><code><var>dir2\/foo2<\/var>.h<\/code> (preferred location \u2014 see details below).<\/li>\n<li>C system files.<\/li>\n<li>C++ system files.<\/li>\n<li>Other libraries&#8217; <code>.h<\/code> files.<\/li>\n<li>Your project&#8217;s <code>.h<\/code> files.<\/li>\n<\/ol>\n<p>The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first <code>.h<\/code> file <code>#include<\/code>d in some <code>.cc<\/code>.<\/p>\n<p><code><var>dir\/foo<\/var>.cc<\/code> and <code><var>dir2\/foo2<\/var>.h<\/code> are often in the same directory (e.g. <code>base\/basictypes_test.cc<\/code> and <code>base\/basictypes.h<\/code>), but can be in different directories too.<\/p>\n<p>Within each section it is nice to order the includes alphabetically.<\/p>\n<p>For example, the includes in <code>google-awesome-project\/src\/foo\/internal\/fooserver.cc<\/code> might look like this:<\/p>\n<div>\n<pre>#include \"foo\/public\/fooserver.h\"  \/\/ Preferred location.\r\n\r\n#include &lt;sys\/types.h&gt;\r\n#include &lt;unistd.h&gt;\r\n\r\n#include &lt;hash_map&gt;\r\n#include &lt;vector&gt;\r\n\r\n#include \"base\/basictypes.h\"\r\n#include \"base\/commandlineflags.h\"\r\n#include \"foo\/public\/bar.h\"<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Scoping\">Scoping<\/h2>\n<div>\n<h3><a id=\"Namespaces\" name=\"Namespaces\">Namespaces<\/a><\/h3>\n<p><span id=\"link-Namespaces__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Namespaces#Namespaces\">link <\/a><\/span><span id=\"Namespaces__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Namespaces__body','Namespaces__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Unnamed namespaces in <code>.cc<\/code> files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a <em>using-directive<\/em>.<\/div>\n<div>\n<div id=\"Namespaces__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span><\/p>\n<p>Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.<\/p>\n<p>For example, if two different projects have a class <code>Foo<\/code> in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, <code>project1::Foo<\/code> and <code>project2::Foo<\/code> are now distinct symbols that do not collide.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span><\/p>\n<p>Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes.<\/p>\n<p>Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR).<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Use namespaces according to the policy described below.<\/p>\n<p><span class=\"stylepoint_subsection\">Unnamed Namespaces<\/span><\/p>\n<ul>\n<li>Unnamed namespaces are allowed and even encouraged in <code>.cc<\/code> files, to avoid runtime naming conflicts:\n<div>\n<pre>namespace {                           \/\/ This is in a .cc file.\r\n\r\n\/\/ The content of a namespace is not indented\r\nenum { kUnused, kEOF, kError };       \/\/ Commonly used tokens.\r\nbool AtEof() { return pos_ == kEOF; }  \/\/ Uses our namespace's EOF.\r\n\r\n}  \/\/ namespace<\/pre>\n<\/div>\n<p>However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment <code>\/\/ namespace<\/code>.<\/li>\n<li>Do not use unnamed namespaces in <code>.h<\/code> files.<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Named Namespaces<\/span><\/p>\n<p>Named namespaces should be used as follows:<\/p>\n<ul>\n<li>Namespaces wrap the entire source file after includes, <a href=\"http:\/\/google-gflags.googlecode.com\/\">gflags<\/a> definitions\/declarations, and forward declarations of classes from other namespaces:\n<div>\n<pre>\/\/ In the .h file\r\nnamespace mynamespace {\r\n\r\n\/\/ All declarations are within the namespace scope.\r\n\/\/ Notice the lack of indentation.\r\nclass MyClass {\r\n public:\r\n  ...\r\n  void Foo();\r\n};\r\n\r\n}  \/\/ namespace mynamespace<\/pre>\n<\/div>\n<div>\n<pre>\/\/ In the .cc file\r\nnamespace mynamespace {\r\n\r\n\/\/ Definition of functions is within scope of the namespace.\r\nvoid MyClass::Foo() {\r\n  ...\r\n}\r\n\r\n}  \/\/ namespace mynamespace<\/pre>\n<\/div>\n<p>The typical <code>.cc<\/code> file might have more complex detail, including the need to reference classes in other namespaces.<\/p>\n<div>\n<pre>#include \"a.h\"\r\n\r\nDEFINE_bool(someflag, false, \"dummy flag\");\r\n\r\nclass C;  \/\/ Forward declaration of class C in the global namespace.\r\nnamespace a { class A; }  \/\/ Forward declaration of a::A.\r\n\r\nnamespace b {\r\n\r\n...code for b...         \/\/ Code goes against the left margin.\r\n\r\n}  \/\/ namespace b<\/pre>\n<\/div>\n<\/li>\n<li>Do not declare anything in namespace <code>std<\/code>, not even forward declarations of standard library classes. Declaring entities in namespace <code>std<\/code> is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file.<\/li>\n<li>You may not use a <em>using-directive<\/em> to make all names from a namespace available.\n<div>\n<pre class=\"badcode\">\/\/ Forbidden -- This pollutes the namespace.\r\nusing namespace foo;<\/pre>\n<\/div>\n<\/li>\n<li>You may use a <em>using-declaration<\/em> anywhere in a <code>.cc<\/code> file, and in functions, methods or classes in <code>.h<\/code> files.\n<div>\n<pre>\/\/ OK in .cc files.\r\n\/\/ Must be in a function, method or class in .h files.\r\nusing ::foo::bar;<\/pre>\n<\/div>\n<\/li>\n<li>Namespace aliases are allowed anywhere in a <code>.cc<\/code> file, anywhere inside the named namespace that wraps an entire <code>.h<\/code> file, and in functions and methods.\n<div>\n<pre>\/\/ Shorten access to some commonly used names in .cc files.\r\nnamespace fbz = ::foo::bar::baz;\r\n\r\n\/\/ Shorten access to some commonly used names (in a .h file).\r\nnamespace librarian {\r\n\/\/ The following alias is available to all files including\r\n\/\/ this header (in namespace librarian):\r\n\/\/ alias names should therefore be chosen consistently\r\n\/\/ within a project.\r\nnamespace pd_s = ::pipeline_diagnostics::sidetable;\r\n\r\ninline void my_inline_function() {\r\n  \/\/ namespace alias local to a function (or method).\r\n  namespace fbz = ::foo::bar::baz;\r\n  ...\r\n}\r\n}  \/\/ namespace librarian<\/pre>\n<\/div>\n<p>Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible.<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Nested_Classes\" name=\"Nested_Classes\">Nested Classes<\/a><\/h3>\n<p><span id=\"link-Nested_Classes__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Nested_Classes#Nested_Classes\">link <\/a><\/span><span id=\"Nested_Classes__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Nested_Classes__body','Nested_Classes__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Although you may use public nested classes when they are part of an interface, consider a <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespaces\">namespace<\/a> to keep declarations out of the global scope.<\/div>\n<div>\n<div id=\"Nested_Classes__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>A class can define another class within it; this is also called a <em>member class<\/em>.<\/p>\n<div>\n<pre>class Foo {\r\n\r\n private:\r\n  \/\/ Bar is a member class, nested within Foo.\r\n  class Bar {\r\n    ...\r\n  };\r\n\r\n};<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the <code>.cc<\/code> file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a <code>Foo::Bar*<\/code> pointer will have to include the full class declaration for <code>Foo<\/code>.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Nonmember,_Static_Member,_and_Global_Functions\" name=\"Nonmember,_Static_Member,_and_Global_Functions\">Nonmember, Static Member, and Global Functions<\/a><\/h3>\n<p><span id=\"link-Nonmember,_Static_Member,_and_Global_Functions__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Nonmember,_Static_Member,_and_Global_Functions#Nonmember,_Static_Member,_and_Global_Functions\">link <\/a><\/span><span id=\"Nonmember,_Static_Member,_and_Global_Functions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Nonmember,_Static_Member,_and_Global_Functions__body','Nonmember,_Static_Member,_and_Global_Functions__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely.<\/div>\n<div>\n<div id=\"Nonmember,_Static_Member,_and_Global_Functions__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Pros: <\/span>Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespaces\">namespaces<\/a> instead.<\/p>\n<p>Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library.<\/p>\n<p>If you must define a nonmember function and it is only needed in its <code>.cc<\/code> file, use an unnamed <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespaces\">namespace<\/a> or <code>static<\/code> linkage (eg <code>static int Foo() {...}<\/code>) to limit its scope.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Local_Variables\" name=\"Local_Variables\">Local Variables<\/a><\/h3>\n<p><span id=\"link-Local_Variables__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Local_Variables#Local_Variables\">link <\/a><\/span><span id=\"Local_Variables__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Local_Variables__body','Local_Variables__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Place a function&#8217;s variables in the narrowest scope possible, and initialize variables in the declaration.<\/div>\n<div>\n<div id=\"Local_Variables__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.<\/p>\n<div>\n<pre class=\"badcode\">int i;\r\ni = f();      \/\/ Bad -- initialization separate from declaration.<\/pre>\n<\/div>\n<div>\n<pre>int j = g();  \/\/ Good -- declaration has initialization.<\/pre>\n<\/div>\n<p>Note that gcc implements <code>for (int i = 0; i &lt; 10; ++i)<\/code> correctly (the scope of <code>i<\/code> is only the scope of the <code>for<\/code> loop), so you can then reuse <code>i<\/code> in another <code>for<\/code> loop in the same scope. It also correctly scopes declarations in <code>if<\/code> and <code>while<\/code> statements, e.g.<\/p>\n<div>\n<pre>while (const char* p = strchr(str, '\/')) str = p + 1;<\/pre>\n<\/div>\n<p>There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope.<\/p>\n<div>\n<pre class=\"badcode\">\/\/ Inefficient implementation:\r\nfor (int i = 0; i &lt; 1000000; ++i) {\r\n  Foo f;  \/\/ My ctor and dtor get called 1000000 times each.\r\n  f.DoSomething(i);\r\n}<\/pre>\n<\/div>\n<p>It may be more efficient to declare such a variable used in a loop outside that loop:<\/p>\n<div>\n<pre>Foo f;  \/\/ My ctor and dtor get called once each.\r\nfor (int i = 0; i &lt; 1000000; ++i) {\r\n  f.DoSomething(i);\r\n}<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Static_and_Global_Variables\" name=\"Static_and_Global_Variables\">Static and Global Variables<\/a><\/h3>\n<p><span id=\"link-Static_and_Global_Variables__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Static_and_Global_Variables#Static_and_Global_Variables\">link <\/a><\/span><span id=\"Static_and_Global_Variables__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Static_and_Global_Variables__body','Static_and_Global_Variables__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction.<\/div>\n<div>\n<div id=\"Static_and_Global_Variables__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays\/structs of POD.<\/p>\n<p>The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals.<\/p>\n<p>Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running &#8212; perhaps in another thread &#8212; tries to access it and fails. Or the destructor for a static &#8216;string&#8217; variable might be run prior to the destructor for another variable that contains a reference to that string.<\/p>\n<p>As a result we only allow static variables to contain POD data. This rule completely disallows <code>vector<\/code> (use C arrays instead), or <code>string<\/code> (use <code>const char []<\/code>).<\/p>\n<p>If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a &#8220;smart&#8221; pointer, since the smart pointer&#8217;s destructor will have the order-of-destructor issue that we are trying to avoid.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Classes\">Classes<\/h2>\n<p>Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don&#8217;ts you should follow when writing a class.<\/p>\n<div>\n<h3><a id=\"Doing_Work_in_Constructors\" name=\"Doing_Work_in_Constructors\">Doing Work in Constructors<\/a><\/h3>\n<p><span id=\"link-Doing_Work_in_Constructors__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Doing_Work_in_Constructors#Doing_Work_in_Constructors\">link <\/a><\/span><span id=\"Doing_Work_in_Constructors__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Doing_Work_in_Constructors__body','Doing_Work_in_Constructors__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit <code>Init()<\/code> method.<\/div>\n<div>\n<div id=\"Doing_Work_in_Constructors__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>It is possible to perform initialization in the body of the constructor.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Convenience in typing. No need to worry about whether the class has been initialized or not.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>The problems with doing work in constructors are:<\/p>\n<ul>\n<li>There is no easy way for constructors to signal errors, short of using exceptions (which are <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Exceptions\">forbidden<\/a>).<\/li>\n<li>If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state.<\/li>\n<li>If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion.<\/li>\n<li>If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before <code>main()<\/code>, possibly breaking some implicit assumptions in the constructor code. For instance, <a href=\"http:\/\/google-gflags.googlecode.com\/\">gflags<\/a> will not yet have been initialized.<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>If your object requires non-trivial initialization, consider having an explicit <code>Init()<\/code> method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Default_Constructors\" name=\"Default_Constructors\">Default Constructors<\/a><\/h3>\n<p><span id=\"link-Default_Constructors__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Default_Constructors#Default_Constructors\">link <\/a><\/span><span id=\"Default_Constructors__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Default_Constructors__body','Default_Constructors__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly.<\/div>\n<div>\n<div id=\"Default_Constructors__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>The default constructor is called when we <code>new<\/code> a class object with no arguments. It is always called when calling <code>new[]<\/code> (for arrays).<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Initializing structures by default, to hold &#8220;impossible&#8221; values, makes debugging much easier.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Extra work for you, the code writer.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid.<\/p>\n<p>The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly.<\/p>\n<p>If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Explicit_Constructors\" name=\"Explicit_Constructors\">Explicit Constructors<\/a><\/h3>\n<p><span id=\"link-Explicit_Constructors__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Explicit_Constructors#Explicit_Constructors\">link <\/a><\/span><span id=\"Explicit_Constructors__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Explicit_Constructors__body','Explicit_Constructors__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Use the C++ keyword <code>explicit<\/code> for constructors with one argument.<\/div>\n<div>\n<div id=\"Explicit_Constructors__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define <code>Foo::Foo(string name)<\/code> and then pass a string to a function that expects a <code>Foo<\/code>, the constructor will be called to convert the string into a <code>Foo<\/code> and will pass the <code>Foo<\/code> to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor <code>explicit<\/code> prevents it from being invoked implicitly as a conversion.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Avoids undesirable conversions.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>None.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>We require all single argument constructors to be explicit. Always put <code>explicit<\/code> in front of one-argument constructors in the class definition: <code>explicit Foo(string name);<\/code><\/p>\n<p>The exception is copy constructors, which, in the rare cases when we allow them, should probably not be <code>explicit<\/code>. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Copy_Constructors\" name=\"Copy_Constructors\">Copy Constructors<\/a><\/h3>\n<p><span id=\"link-Copy_Constructors__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Copy_Constructors#Copy_Constructors\">link <\/a><\/span><span id=\"Copy_Constructors__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Copy_Constructors__body','Copy_Constructors__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with <code>DISALLOW_COPY_AND_ASSIGN<\/code>.<\/div>\n<div>\n<div id=\"Copy_Constructors__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than <code>CopyFrom()<\/code>-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container.<\/p>\n<p>If your class needs to be copyable, prefer providing a copy method, such as <code>CopyFrom()<\/code> or <code>Clone()<\/code>, rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator.<\/p>\n<p>If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the <code>private:<\/code> section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error).<\/p>\n<p>For convenience, a <code>DISALLOW_COPY_AND_ASSIGN<\/code> macro can be used:<\/p>\n<div>\n<pre>\/\/ A macro to disallow the copy constructor and operator= functions\r\n\/\/ This should be used in the private: declarations for a class\r\n#define DISALLOW_COPY_AND_ASSIGN(TypeName) \\\r\n  TypeName(const TypeName&amp;);               \\\r\n  void operator=(const TypeName&amp;)<\/pre>\n<\/div>\n<p>Then, in <code>class Foo<\/code>:<\/p>\n<div>\n<pre>class Foo {\r\n public:\r\n  Foo(int f);\r\n  ~Foo();\r\n\r\n private:\r\n  DISALLOW_COPY_AND_ASSIGN(Foo);\r\n};<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Structs_vs._Classes\" name=\"Structs_vs._Classes\">Structs vs. Classes<\/a><\/h3>\n<p><span id=\"link-Structs_vs._Classes__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Structs_vs._Classes#Structs_vs._Classes\">link <\/a><\/span><span id=\"Structs_vs._Classes__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Structs_vs._Classes__body','Structs_vs._Classes__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Use a <code>struct<\/code> only for passive objects that carry data; everything else is a <code>class<\/code>.<\/div>\n<div>\n<div id=\"Structs_vs._Classes__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p>The <code>struct<\/code> and <code>class<\/code> keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you&#8217;re defining.<\/p>\n<p><code>structs<\/code> should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access\/setting the data members. The accessing\/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, <code>Initialize()<\/code>, <code>Reset()<\/code>, <code>Validate()<\/code>.<\/p>\n<p>If more functionality is required, a <code>class<\/code> is more appropriate. If in doubt, make it a <code>class<\/code>.<\/p>\n<p>For consistency with STL, you can use <code>struct<\/code> instead of <code>class<\/code> for functors and traits.<\/p>\n<p>Note that member variables in structs and classes have <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Variable_Names\">different naming rules<\/a>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Inheritance\" name=\"Inheritance\">Inheritance<\/a><\/h3>\n<p><span id=\"link-Inheritance__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Inheritance#Inheritance\">link <\/a><\/span><span id=\"Inheritance__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Inheritance__body','Inheritance__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Composition is often more appropriate than inheritance. When using inheritance, make it <code>public<\/code>.<\/div>\n<div>\n<div id=\"Inheritance__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Interfaces\">interface inheritance<\/a>, in which only method names are inherited.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>All inheritance should be <code>public<\/code>. If you want to do private inheritance, you should be including an instance of the base class as a member instead.<\/p>\n<p>Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the &#8220;is-a&#8221; case: <code>Bar<\/code> subclasses <code>Foo<\/code> if it can reasonably be said that <code>Bar<\/code> &#8220;is a kind of&#8221; <code>Foo<\/code>.<\/p>\n<p>Make your destructor <code>virtual<\/code> if necessary. If your class has virtual methods, its destructor should be virtual.<\/p>\n<p>Limit the use of <code>protected<\/code> to those member functions that might need to be accessed from subclasses. Note that <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Access_Control\">data members should be private<\/a>.<\/p>\n<p>When redefining an inherited virtual function, explicitly declare it <code>virtual<\/code> in the declaration of the derived class. Rationale: If <code>virtual<\/code> is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Multiple_Inheritance\" name=\"Multiple_Inheritance\">Multiple Inheritance<\/a><\/h3>\n<p><span id=\"link-Multiple_Inheritance__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Multiple_Inheritance#Multiple_Inheritance\">link <\/a><\/span><span id=\"Multiple_Inheritance__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Multiple_Inheritance__body','Multiple_Inheritance__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Interfaces\">pure interface<\/a> classes tagged with the <code>Interface<\/code> suffix.<\/div>\n<div>\n<div id=\"Multiple_Inheritance__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are <em>pure interfaces<\/em> and those that have an <em>implementation<\/em>.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Multiple implementation inheritance may let you re-use even more code than single inheritance (see <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Inheritance\">Inheritance<\/a>).<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Only very rarely is multiple <em>implementation<\/em> inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Interfaces\">pure interfaces<\/a>. In order to ensure that they remain pure interfaces, they must end with the <code>Interface<\/code> suffix.<\/p>\n<p><span class=\"stylepoint_subsection\">Note:<\/span> There is an <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Windows_Code\">exception<\/a> to this rule on Windows.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Interfaces\" name=\"Interfaces\">Interfaces<\/a><\/h3>\n<p><span id=\"link-Interfaces__button\" class=\"link_button\" style=\"display: block;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Interfaces#Interfaces\">link <\/a><\/span><span id=\"Interfaces__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Interfaces__body','Interfaces__button')\">\u25bd<\/span><\/p>\n<div style=\"display: inline;\">Classes that satisfy certain conditions are allowed, but not required, to end with an <code>Interface<\/code> suffix.<\/div>\n<div>\n<div id=\"Interfaces__body\" class=\"stylepoint_body\" style=\"display: inline;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span><\/p>\n<p>A class is a pure interface if it meets the following requirements:<\/p>\n<ul>\n<li>It has only public pure virtual (&#8220;<code>= 0<\/code>&#8220;) methods and static methods (but see below for destructor).<\/li>\n<li>It may not have non-static data members.<\/li>\n<li>It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected.<\/li>\n<li>If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the <code>Interface<\/code> suffix.<\/li>\n<\/ul>\n<p>An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, <cite>The C++ Programming Language<\/cite>, 3rd edition, section 12.4 for details.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Tagging a class with the <code>Interface<\/code> suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Multiple_Inheritance\">multiple inheritance<\/a>. Additionally, the interface concept is already well-understood by Java programmers.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>The <code>Interface<\/code> suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn&#8217;t be exposed to clients.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>A class may end with <code>Interface<\/code> only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with <code>Interface<\/code>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Operator_Overloading\" name=\"Operator_Overloading\">Operator Overloading<\/a><\/h3>\n<p><span id=\"link-Operator_Overloading__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Operator_Overloading#Operator_Overloading\">link <\/a><\/span><span id=\"Operator_Overloading__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Operator_Overloading__body','Operator_Overloading__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Do not overload operators except in rare, special circumstances.<\/div>\n<div>\n<div id=\"Operator_Overloading__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>A class can define that operators such as <code>+<\/code> and <code>\/<\/code> operate on the class as if it were a built-in type.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Can make code appear more intuitive because a class will behave in the same way as built-in types (such as <code>int<\/code>). Overloaded operators are more playful names for functions that are less-colorfully named, such as <code>Equals()<\/code> or <code>Add()<\/code>. For some template functions to work correctly, you may need to define operators.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>While operator overloading can make code more intuitive, it has several drawbacks:<\/p>\n<ul>\n<li>It can fool our intuition into thinking that expensive operations are cheap, built-in operations.<\/li>\n<li>It is much harder to find the call sites for overloaded operators. Searching for <code>Equals()<\/code> is much easier than searching for relevant invocations of <code>==<\/code>.<\/li>\n<li>Some operators work on pointers too, making it easy to introduce bugs. <code>Foo + 4<\/code> may do one thing, while <code>&amp;Foo + 4<\/code> does something totally different. The compiler does not complain for either of these, making this very hard to debug.<\/li>\n<\/ul>\n<p>Overloading also has surprising ramifications. For instance, if a class overloads unary <code>operator&amp;<\/code>, it cannot safely be forward-declared.\u00a0<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>In general, do not overload operators. The assignment operator (<code>operator=<\/code>), in particular, is insidious and should be avoided. You can define functions like <code>Equals()<\/code> and <code>CopyFrom()<\/code> if you need them. Likewise, avoid the dangerous unary <code>operator&amp;<\/code> at all costs, if there&#8217;s any possibility the class might be forward-declared.<\/p>\n<p>However, there may be rare cases where you need to overload an operator to interoperate with templates or &#8220;standard&#8221; C++ classes (such as <code>operator&lt;&lt;(ostream&amp;, const T&amp;)<\/code> for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload <code>operator==<\/code> or <code>operator&lt;<\/code> just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container.<\/p>\n<p>Some of the STL algorithms do require you to overload <code>operator==<\/code>, and you may do so in these cases, provided you document why.<\/p>\n<p>See also <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Copy_Constructors\">Copy Constructors<\/a> and <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Overloading\">Function Overloading<\/a>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Access_Control\" name=\"Access_Control\">Access Control<\/a><\/h3>\n<p><span id=\"link-Access_Control__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Access_Control#Access_Control\">link <\/a><\/span><span id=\"Access_Control__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Access_Control__body','Access_Control__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Make data members <code>private<\/code>, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be <code>protected<\/code> when using <a href=\"http:\/\/code.google.com\/p\/googletest\/\">Google Test<\/a>). Typically a variable would be called <code>foo_<\/code> and the accessor function <code>foo()<\/code>. You may also want a mutator function <code>set_foo()<\/code>. Exception: <code>static const<\/code> data members (typically called <code>kFoo<\/code>) need not be <code>private<\/code>.<\/div>\n<div>\n<div id=\"Access_Control__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>The definitions of accessors are usually inlined in the header file.<\/p>\n<p>See also <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Inheritance\">Inheritance<\/a> and <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Names\">Function Names<\/a>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Declaration_Order\" name=\"Declaration_Order\">Declaration Order<\/a><\/h3>\n<p><span id=\"link-Declaration_Order__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Declaration_Order#Declaration_Order\">link <\/a><\/span><span id=\"Declaration_Order__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Declaration_Order__body','Declaration_Order__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use the specified order of declarations within a class: <code>public:<\/code> before <code>private:<\/code>, methods before data members (variables), etc.<\/div>\n<div>\n<div id=\"Declaration_Order__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Your class definition should start with its <code>public:<\/code> section, followed by its <code>protected:<\/code> section and then its <code>private:<\/code> section. If any of these sections are empty, omit them.<\/p>\n<p>Within each section, the declarations generally should be in the following order:<\/p>\n<ul>\n<li>Typedefs and Enums<\/li>\n<li>Constants (<code>static const<\/code> data members)<\/li>\n<li>Constructors<\/li>\n<li>Destructor<\/li>\n<li>Methods, including static methods<\/li>\n<li>Data Members (except <code>static const<\/code> data members)<\/li>\n<\/ul>\n<p>Friend declarations should always be in the private section, and the <code>DISALLOW_COPY_AND_ASSIGN<\/code> macro invocation should be at the end of the <code>private:<\/code> section. It should be the last thing in the class. See <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Copy_Constructors\">Copy Constructors<\/a>.<\/p>\n<p>Method definitions in the corresponding <code>.cc<\/code> file should be the same as the declaration order, as much as possible.<\/p>\n<p>Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Inline_Functions\">Inline Functions<\/a> for more details.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Write_Short_Functions\" name=\"Write_Short_Functions\">Write Short Functions<\/a><\/h3>\n<p><span id=\"link-Write_Short_Functions__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Write_Short_Functions#Write_Short_Functions\">link <\/a><\/span><span id=\"Write_Short_Functions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Write_Short_Functions__body','Write_Short_Functions__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Prefer small and focused functions.<\/div>\n<div>\n<div id=\"Write_Short_Functions__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program.<\/p>\n<p>Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code.<\/p>\n<p>You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Google-Specific_Magic\">Google-Specific Magic<\/h2>\n<p>There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere.<\/p>\n<div>\n<h3><a id=\"Smart_Pointers\" name=\"Smart_Pointers\">Smart Pointers<\/a><\/h3>\n<p><span id=\"link-Smart_Pointers__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Smart_Pointers#Smart_Pointers\">link <\/a><\/span><span id=\"Smart_Pointers__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Smart_Pointers__body','Smart_Pointers__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">If you actually need pointer semantics, <code>scoped_ptr<\/code> is great. You should only use <code>std::tr1::shared_ptr<\/code> under very specific conditions, such as when objects need to be held by STL containers. You should never use <code>auto_ptr<\/code>.<\/div>\n<div>\n<div id=\"Smart_Pointers__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>&#8220;Smart&#8221; pointers are objects that act like pointers but have added semantics. When a <code>scoped_ptr<\/code> is destroyed, for instance, it deletes the object it&#8217;s pointing to. <code>shared_ptr<\/code> is the same way, but implements reference-counting so only the last pointer to an object deletes it.<\/p>\n<p>Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this design is that it is easy to create circular references or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned.<\/p>\n<p>Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"cpplint\" name=\"cpplint\">cpplint<\/a><\/h3>\n<p><span id=\"link-cpplint__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=cpplint#cpplint\">link <\/a><\/span><span id=\"cpplint__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('cpplint__body','cpplint__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use <code>cpplint.py<\/code> to detect style errors.<\/div>\n<div>\n<div id=\"cpplint__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><code>cpplint.py<\/code> is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting <code>\/\/ NOLINT<\/code> at the end of the line.<\/p>\n<p>Some projects have instructions on how to run <code>cpplint.py<\/code> from their project tools. If the project you are contributing to does not, you can download <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cpplint\/cpplint.py\"><code>cpplint.py<\/code><\/a> separately.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Other_C++_Features\">Other C++ Features<\/h2>\n<div>\n<h3><a id=\"Reference_Arguments\" name=\"Reference_Arguments\">Reference Arguments<\/a><\/h3>\n<p><span id=\"link-Reference_Arguments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Reference_Arguments#Reference_Arguments\">link <\/a><\/span><span id=\"Reference_Arguments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Reference_Arguments__body','Reference_Arguments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">All parameters passed by reference must be labeled <code>const<\/code>.<\/div>\n<div>\n<div id=\"Reference_Arguments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>In C, if a function needs to modify a variable, the parameter must use a pointer, eg <code>int foo(int *pval)<\/code>. In C++, the function can alternatively declare a reference parameter: <code>int foo(int &amp;val)<\/code>.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Defining a parameter as reference avoids ugly code like <code>(*pval)++<\/code>. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that <code>NULL<\/code> is not a possible value.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>References can be confusing, as they have value syntax but pointer semantics.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Within function parameter lists all references must be <code>const<\/code>:<\/p>\n<div>\n<pre>void Foo(const string &amp;in, string *out);<\/pre>\n<\/div>\n<p>In fact it is a very strong convention in Google code that input arguments are values or <code>const<\/code> references while output arguments are pointers. Input parameters may be <code>const<\/code> pointers, but we never allow non-<code>const<\/code> reference parameters.<\/p>\n<p>One case when you might want an input parameter to be a <code>const<\/code> pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as <code>bind2nd<\/code> and <code>mem_fun<\/code> do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Function_Overloading\" name=\"Function_Overloading\">Function Overloading<\/a><\/h3>\n<p><span id=\"link-Function_Overloading__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Function_Overloading#Function_Overloading\">link <\/a><\/span><span id=\"Function_Overloading__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Function_Overloading__body','Function_Overloading__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called.<\/div>\n<div>\n<div id=\"Function_Overloading__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span><\/p>\n<p>You may write a function that takes a <code>const string&amp;<\/code> and overload it with another that takes <code>const char*<\/code>.<\/p>\n<div>\n<pre>class MyClass {\r\n public:\r\n  void Analyze(const string &amp;text);\r\n  void Analyze(const char *text, size_t textlen);\r\n};<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>If a function is overloaded by the argument types alone, a reader may have to understand C++&#8217;s complex matching rules in order to tell what&#8217;s going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., <code>AppendString()<\/code>, <code>AppendInt()<\/code> rather than just <code>Append()<\/code>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Default_Arguments\" name=\"Default_Arguments\">Default Arguments<\/a><\/h3>\n<p><span id=\"link-Default_Arguments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Default_Arguments#Default_Arguments\">link <\/a><\/span><span id=\"Default_Arguments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Default_Arguments__body','Default_Arguments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">We do not allow default function parameters, except in a few uncommon situations explained below.<\/div>\n<div>\n<div id=\"Default_Arguments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Pros: <\/span>Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>People often figure out how to use an API by looking at existing code that uses it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of.<\/p>\n<p>One specific exception is when default arguments are used to simulate variable-length argument lists.<\/p>\n<div>\n<pre>\/\/ Support up to 4 params by using a default empty AlphaNum.\r\nstring StrCat(const AlphaNum &amp;a,\r\n              const AlphaNum &amp;b = gEmptyAlphaNum,\r\n              const AlphaNum &amp;c = gEmptyAlphaNum,\r\n              const AlphaNum &amp;d = gEmptyAlphaNum);<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Variable-Length_Arrays_and_alloca__\" name=\"Variable-Length_Arrays_and_alloca__\">Variable-Length Arrays and alloca()<\/a><\/h3>\n<p><span id=\"link-Variable-Length_Arrays_and_alloca____button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Variable-Length_Arrays_and_alloca__#Variable-Length_Arrays_and_alloca__\">link <\/a><\/span><span id=\"Variable-Length_Arrays_and_alloca____button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Variable-Length_Arrays_and_alloca____body','Variable-Length_Arrays_and_alloca____button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">We do not allow variable-length arrays or <code>alloca()<\/code>.<\/div>\n<div>\n<div id=\"Variable-Length_Arrays_and_alloca____body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Pros: <\/span>Variable-length arrays have natural-looking syntax. Both variable-length arrays and <code>alloca()<\/code> are very efficient.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: &#8220;It ran fine on my machine, but dies mysteriously in production&#8221;.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>Use a safe allocator instead, such as <code>scoped_ptr<\/code>\/<code>scoped_array<\/code>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Friends\" name=\"Friends\">Friends<\/a><\/h3>\n<p><span id=\"link-Friends__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Friends#Friends\">link <\/a><\/span><span id=\"Friends__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Friends__body','Friends__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">We allow use of <code>friend<\/code> classes and functions, within reason.<\/div>\n<div>\n<div id=\"Friends__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of <code>friend<\/code> is to have a <code>FooBuilder<\/code> class be a friend of <code>Foo<\/code> so that it can construct the inner state of <code>Foo<\/code> correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests.<\/p>\n<p>Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Exceptions\" name=\"Exceptions\">Exceptions<\/a><\/h3>\n<p><span id=\"link-Exceptions__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Exceptions#Exceptions\">link <\/a><\/span><span id=\"Exceptions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Exceptions__body','Exceptions__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">We do not use C++ exceptions.<\/div>\n<div>\n<div id=\"Exceptions__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Pros: <\/span><\/p>\n<ul>\n<li>Exceptions allow higher levels of an application to decide how to handle &#8220;can&#8217;t happen&#8221; failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes.<\/li>\n<li>Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with.<\/li>\n<li>Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries.<\/li>\n<li>Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an <code>Init()<\/code> method, but these require heap allocation or a new &#8220;invalid&#8221; state, respectively.<\/li>\n<li>Exceptions are really handy in testing frameworks.<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span><\/p>\n<ul>\n<li>When you add a <code>throw<\/code> statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if <code>f()<\/code> calls <code>g()<\/code> calls <code>h()<\/code>, and <code>h<\/code> throws an exception that <code>f<\/code> catches, <code>g<\/code> has to be careful or it may not clean up properly.<\/li>\n<li>More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don&#8217;t expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand.<\/li>\n<li>Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a &#8220;commit&#8221; phase. This will have both benefits and costs (perhaps where you&#8217;re forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they&#8217;re not worth it.<\/li>\n<li>Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure.<\/li>\n<li>The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it&#8217;s not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions!<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.<\/p>\n<p>Given that Google&#8217;s existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don&#8217;t believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden.<\/p>\n<p>Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we&#8217;d like to use our open-source projects at Google and it&#8217;s difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch.<\/p>\n<p>There is an <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Windows_Code\">exception<\/a> to this rule (no pun intended) for Windows code.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Run-Time_Type_Information__RTTI_\" name=\"Run-Time_Type_Information__RTTI_\">Run-Time Type Information (RTTI)<\/a><\/h3>\n<p><span id=\"link-Run-Time_Type_Information__RTTI___button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Run-Time_Type_Information__RTTI_#Run-Time_Type_Information__RTTI_\">link <\/a><\/span><span id=\"Run-Time_Type_Information__RTTI___button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Run-Time_Type_Information__RTTI___body','Run-Time_Type_Information__RTTI___button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">We do not use Run Time Type Information (RTTI).<\/div>\n<div>\n<div id=\"Run-Time_Type_Information__RTTI___body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>RTTI allows a programmer to query the C++ class of an object at run time.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span><\/p>\n<p>It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type.<\/p>\n<p>In rare circumstances, it is useful even outside of tests.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>A query of type during run-time typically means a design problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the design of your class.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type.<\/p>\n<p>Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself.<\/p>\n<p>If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system.<\/p>\n<p>If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. \ud83d\ude42 Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Casting\" name=\"Casting\">Casting<\/a><\/h3>\n<p><span id=\"link-Casting__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Casting#Casting\">link <\/a><\/span><span id=\"Casting__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Casting__body','Casting__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use C++ casts like <code>static_cast&lt;&gt;()<\/code>. Do not use other cast formats like <code>int y = (int)x;<\/code> or <code>int y = int(x);<\/code>.<\/div>\n<div>\n<div id=\"Casting__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>C++ introduced a different cast system from C that distinguishes the types of cast operations.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>The problem with C casts is the ambiguity of the operation; sometimes you are doing a <em>conversion<\/em> (e.g., <code>(int)3.5<\/code>) and sometimes you are doing a <em>cast<\/em> (e.g., <code>(int)\"hello\"<\/code>); C++ casts avoid this. Additionally C++ casts are more visible when searching for them.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>The syntax is nasty.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Do not use C-style casts. Instead, use these C++-style casts.<\/p>\n<ul>\n<li>Use <code>static_cast<\/code> as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass.<\/li>\n<li>Use <code>const_cast<\/code> to remove the <code>const<\/code> qualifier (see <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Use_of_const\">const<\/a>).<\/li>\n<li>Use <code>reinterpret_cast<\/code> to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues.<\/li>\n<li>Do not use <code>dynamic_cast<\/code> except in test code. If you need to know type information at runtime in this way outside of a unittest, you probably have a <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Run-Time_Type_Information__RTTI_\">design flaw<\/a>.<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Streams\" name=\"Streams\">Streams<\/a><\/h3>\n<p><span id=\"link-Streams__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Streams#Streams\">link <\/a><\/span><span id=\"Streams__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Streams__body','Streams__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use streams only for logging.<\/div>\n<div>\n<div id=\"Streams__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>Streams are a replacement for <code>printf()<\/code> and <code>scanf()<\/code>.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with <code>printf<\/code> either.) Streams have automatic constructors and destructors that open and close the relevant files.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Streams make it difficult to do functionality like <code>pread()<\/code>. Some formatting (particularly the common format string idiom <code>%.*s<\/code>) is difficult if not impossible to do efficiently using streams without using <code>printf<\/code>-like hacks. Streams do not support operator reordering (the <code>%1s<\/code> directive), which is helpful for internationalization.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>Do not use streams, except where required by a logging interface. Use <code>printf<\/code>-like routines instead.<\/p>\n<p>There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code.<\/p>\n<p><span class=\"stylepoint_subsection\">Extended Discussion<\/span><\/p>\n<p>There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I\/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using <code>printf<\/code> plus Read\/Write\/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons.<\/p>\n<p>Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams.<\/p>\n<div>\n<pre>cout &lt;&lt; this;  \/\/ Prints the address\r\ncout &lt;&lt; *this;  \/\/ Prints the contents<\/pre>\n<\/div>\n<p>The compiler does not generate an error because <code>&lt;&lt;<\/code> has been overloaded. We discourage overloading for just this reason.<\/p>\n<p>Some say <code>printf<\/code> formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover?<\/p>\n<div>\n<pre>cerr &lt;&lt; \"Error connecting to '\" &lt;&lt; foo-&gt;bar()-&gt;hostname.first\r\n     &lt;&lt; \":\" &lt;&lt; foo-&gt;bar()-&gt;hostname.second &lt;&lt; \": \" &lt;&lt; strerror(errno);\r\n\r\nfprintf(stderr, \"Error connecting to '%s:%u: %s\",\r\n        foo-&gt;bar()-&gt;hostname.first, foo-&gt;bar()-&gt;hostname.second,\r\n        strerror(errno));<\/pre>\n<\/div>\n<p>And so on and so forth for any issue you might bring up. (You could argue, &#8220;Things would be better with the right wrappers,&#8221; but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.)<\/p>\n<p>Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on <code>printf<\/code> + <code>read<\/code>\/<code>write<\/code>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Preincrement_and_Predecrement\" name=\"Preincrement_and_Predecrement\">Preincrement and Predecrement<\/a><\/h3>\n<p><span id=\"link-Preincrement_and_Predecrement__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Preincrement_and_Predecrement#Preincrement_and_Predecrement\">link <\/a><\/span><span id=\"Preincrement_and_Predecrement__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Preincrement_and_Predecrement__body','Preincrement_and_Predecrement__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use prefix form (<code>++i<\/code>) of the increment and decrement operators with iterators and other template objects.<\/div>\n<div>\n<div id=\"Preincrement_and_Predecrement__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>When a variable is incremented (<code>++i<\/code> or <code>i++<\/code>) or decremented (<code>--i<\/code> or <code>i--<\/code>) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement).<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>When the return value is ignored, the &#8220;pre&#8221; form (<code>++i<\/code>) is never less efficient than the &#8220;post&#8221; form (<code>i++<\/code>), and is often more efficient. This is because post-increment (or decrement) requires a copy of <code>i<\/code> to be made, which is the value of the expression. If <code>i<\/code> is an iterator or other non-scalar type, copying <code>i<\/code> could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment?<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>The tradition developed, in C, of using post-increment when the expression value is not used, especially in <code>for<\/code> loops. Some find post-increment easier to read, since the &#8220;subject&#8221; (<code>i<\/code>) precedes the &#8220;verb&#8221; (<code>++<\/code>), just like in English.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Use_of_const\" name=\"Use_of_const\">Use of const<\/a><\/h3>\n<p><span id=\"link-Use_of_const__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Use_of_const#Use_of_const\">link <\/a><\/span><span id=\"Use_of_const__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Use_of_const__body','Use_of_const__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">We strongly recommend that you use <code>const<\/code> whenever it makes sense to do so.<\/div>\n<div>\n<div id=\"Use_of_const__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>Declared variables and parameters can be preceded by the keyword <code>const<\/code> to indicate the variables are not changed (e.g., <code>const int foo<\/code>). Class functions can have the <code>const<\/code> qualifier to indicate the function does not change the state of the class member variables (e.g., <code>class Foo { int Bar(char c) const; };<\/code>).<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span><code>const<\/code> is viral: if you pass a <code>const<\/code> variable to a function, that function must have <code>const<\/code> in its prototype (or the variable will need a <code>const_cast<\/code>). This can be a particular problem when calling library functions.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p><code>const<\/code> variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use <code>const<\/code> whenever it makes sense to do so:<\/p>\n<ul>\n<li>If a function does not modify an argument passed by reference or by pointer, that argument should be <code>const<\/code>.<\/li>\n<li>Declare methods to be <code>const<\/code> whenever possible. Accessors should almost always be <code>const<\/code>. Other methods should be const if they do not modify any data members, do not call any non-<code>const<\/code> methods, and do not return a non-<code>const<\/code> pointer or non-<code>const<\/code> reference to a data member.<\/li>\n<li>Consider making data members <code>const<\/code> whenever they do not need to be modified after construction.<\/li>\n<\/ul>\n<p>However, do not go crazy with <code>const<\/code>. Something like <code>const int * const * const x;<\/code> is likely overkill, even if it accurately describes how const x is. Focus on what&#8217;s really useful to know: in this case, <code>const int** x<\/code> is probably sufficient.<\/p>\n<p>The <code>mutable<\/code> keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first.<\/p>\n<p><span class=\"stylepoint_subsection\">Where to put the const<\/span><\/p>\n<p>Some people favor the form <code>int const *foo<\/code> to <code>const int* foo<\/code>. They argue that this is more readable because it&#8217;s more consistent: it keeps the rule that <code>const<\/code> always follows the object it&#8217;s describing. However, this consistency argument doesn&#8217;t apply in this case, because the &#8220;don&#8217;t go crazy&#8221; dictum eliminates most of the uses you&#8217;d have to be consistent with. Putting the <code>const<\/code> first is arguably more readable, since it follows English in putting the &#8220;adjective&#8221; (<code>const<\/code>) before the &#8220;noun&#8221; (<code>int<\/code>).<\/p>\n<p>That said, while we encourage putting <code>const<\/code> first, we do not require it. But be consistent with the code around you!<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Integer_Types\" name=\"Integer_Types\">Integer Types<\/a><\/h3>\n<p><span id=\"link-Integer_Types__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Integer_Types#Integer_Types\">link <\/a><\/span><span id=\"Integer_Types__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Integer_Types__body','Integer_Types__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Of the built-in C++ integer types, the only one used is <code>int<\/code>. If a program needs a variable of a different size, use a precise-width integer type from <code>&lt;stdint.h&gt;<\/code>, such as <code>int16_t<\/code>.<\/div>\n<div>\n<div id=\"Integer_Types__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>C++ does not specify the sizes of its integer types. Typically people assume that <code>short<\/code> is 16 bits, <code>int<\/code> is 32 bits, <code>long<\/code> is 32 bits and <code>long long<\/code> is 64 bits.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Uniformity of declaration.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>The sizes of integral types in C++ can vary based on compiler and architecture.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p><code>&lt;stdint.h&gt;<\/code> defines types like <code>int16_t<\/code>, <code>uint32_t<\/code>, <code>int64_t<\/code>, etc. You should always use those in preference to <code>short<\/code>, <code>unsigned long long<\/code> and the like, when you need a guarantee on the size of an integer. Of the C integer types, only <code>int<\/code> should be used. When appropriate, you are welcome to use standard types like <code>size_t<\/code> and <code>ptrdiff_t<\/code>.<\/p>\n<p>We use <code>int<\/code> very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old <code>int<\/code> for such things. You should assume that an <code>int<\/code> is at least 32 bits, but don&#8217;t assume that it has more than 32 bits. If you need a 64-bit integer type, use <code>int64_t<\/code> or <code>uint64_t<\/code>.<\/p>\n<p>For integers we know can be &#8220;big&#8221;, use <code>int64_t<\/code>.<\/p>\n<p>You should not use the unsigned integer types such as <code>uint32_t<\/code>, unless the quantity you are representing is really a bit pattern rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this.<\/p>\n<p><span class=\"stylepoint_subsection\">On Unsigned Integers<\/span><\/p>\n<p>Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider:<\/p>\n<div>\n<pre>for (unsigned int i = foo.Length()-1; i &gt;= 0; --i) ...<\/pre>\n<\/div>\n<p>This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C&#8217;s type-promotion scheme causes unsigned types to behave differently than one might expect.<\/p>\n<p>So, document that a variable is non-negative using assertions. Don&#8217;t use an unsigned type.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"64-bit_Portability\" name=\"64-bit_Portability\">64-bit Portability<\/a><\/h3>\n<p><span id=\"link-64-bit_Portability__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=64-bit_Portability#64-bit_Portability\">link <\/a><\/span><span id=\"64-bit_Portability__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('64-bit_Portability__body','64-bit_Portability__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment.<\/div>\n<div>\n<div id=\"64-bit_Portability__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<ul>\n<li><code>printf()<\/code> specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file <code>inttypes.h<\/code>):\n<div>\n<pre>\/\/ printf macros for size_t, in the style of inttypes.h\r\n#ifdef _LP64\r\n#define __PRIS_PREFIX \"z\"\r\n#else\r\n#define __PRIS_PREFIX\r\n#endif\r\n\r\n\/\/ Use these macros after a % in a printf format string\r\n\/\/ to get correct 32\/64 bit behavior, like this:\r\n\/\/ size_t size = records.size();\r\n\/\/ printf(\"%\"PRIuS\"\\n\", size);\r\n\r\n#define PRIdS __PRIS_PREFIX \"d\"\r\n#define PRIxS __PRIS_PREFIX \"x\"\r\n#define PRIuS __PRIS_PREFIX \"u\"\r\n#define PRIXS __PRIS_PREFIX \"X\"\r\n#define PRIoS __PRIS_PREFIX \"o\"<\/pre>\n<\/div>\n<table border=\"1\" summary=\"portable printf specifiers\">\n<tbody>\n<tr align=\"center\">\n<th>Type<\/th>\n<th>DO NOT use<\/th>\n<th>DO use<\/th>\n<th>Notes<\/th>\n<\/tr>\n<tr align=\"center\">\n<td><code>void *<\/code> (or any pointer)<\/td>\n<td><code>%lx<\/code><\/td>\n<td><code>%p<\/code><\/td>\n<td>\u00a0<\/td>\n<\/tr>\n<tr align=\"center\">\n<td><code>int64_t<\/code><\/td>\n<td><code>%qd<\/code>, <code>%lld<\/code><\/td>\n<td><code>%\"PRId64\"<\/code><\/td>\n<td>\u00a0<\/td>\n<\/tr>\n<tr align=\"center\">\n<td><code>uint64_t<\/code><\/td>\n<td><code>%qu<\/code>, <code>%llu<\/code>, <code>%llx<\/code><\/td>\n<td><code>%\"PRIu64\"<\/code>, <code>%\"PRIx64\"<\/code><\/td>\n<td>\u00a0<\/td>\n<\/tr>\n<tr align=\"center\">\n<td><code>size_t<\/code><\/td>\n<td><code>%u<\/code><\/td>\n<td><code>%\"PRIuS\"<\/code>, <code>%\"PRIxS\"<\/code><\/td>\n<td>C99 specifies <code>%zu<\/code><\/td>\n<\/tr>\n<tr align=\"center\">\n<td><code>ptrdiff_t<\/code><\/td>\n<td><code>%d<\/code><\/td>\n<td><code>%\"PRIdS\"<\/code><\/td>\n<td>C99 specifies <code>%zd<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Note that the <code>PRI*<\/code> macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the <code>%<\/code> when using the <code>PRI*<\/code> macros. So, e.g. <code>printf(\"x = %30\"PRIuS\"\\n\", x)<\/code> would expand on 32-bit Linux to <code>printf(\"x = %30\" \"u\" \"\\n\", x)<\/code>, which the compiler will treat as <code>printf(\"x = %30u\\n\", x)<\/code>.<\/li>\n<li>Remember that <code>sizeof(void *)<\/code> != <code>sizeof(int)<\/code>. Use <code>intptr_t<\/code> if you want a pointer-sized integer.<\/li>\n<li>You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class\/structure with a <code>int64_t<\/code>\/<code>uint64_t<\/code> member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use <code>__attribute__((packed))<\/code>. MSVC offers <code>#pragma pack()<\/code> and <code>__declspec(align())<\/code>.<\/li>\n<li>Use the <code>LL<\/code> or <code>ULL<\/code> suffixes as needed to create 64-bit constants. For example:\n<div>\n<pre>int64_t my_value = 0x123456789LL;\r\nuint64_t my_mask = 3ULL &lt;&lt; 48;<\/pre>\n<\/div>\n<\/li>\n<li>If you really need different code on 32-bit and 64-bit systems, use <code>#ifdef _LP64<\/code> to choose between the code variants. (But please avoid this if possible, and keep any such changes localized.)<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Preprocessor_Macros\" name=\"Preprocessor_Macros\">Preprocessor Macros<\/a><\/h3>\n<p><span id=\"link-Preprocessor_Macros__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Preprocessor_Macros#Preprocessor_Macros\">link <\/a><\/span><span id=\"Preprocessor_Macros__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Preprocessor_Macros__body','Preprocessor_Macros__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Be very cautious with macros. Prefer inline functions, enums, and <code>const<\/code> variables to macros.<\/div>\n<div>\n<div id=\"Preprocessor_Macros__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Macros mean that the code you see is not the same as the code the compiler sees. This can introduce unexpected behavior, especially since macros have global scope.<\/p>\n<p>Luckily, macros are not nearly as necessary in C++ as they are in C. Instead of using a macro to inline performance-critical code, use an inline function. Instead of using a macro to store a constant, use a <code>const<\/code> variable. Instead of using a macro to &#8220;abbreviate&#8221; a long variable name, use a reference. Instead of using a macro to conditionally compile code &#8230; well, don&#8217;t do that at all (except, of course, for the <code>#define<\/code> guards to prevent double inclusion of header files). It makes testing much more difficult.<\/p>\n<p>Macros can do things these other techniques cannot, and you do see them in the codebase, especially in the lower-level libraries. And some of their special features (like stringifying, concatenation, and so forth) are not available through the language proper. But before using a macro, consider carefully whether there&#8217;s a non-macro way to achieve the same result.<\/p>\n<p>The following usage pattern will avoid many problems with macros; if you use macros, follow it whenever possible:<\/p>\n<ul>\n<li>Don&#8217;t define macros in a <code>.h<\/code> file.<\/li>\n<li><code>#define<\/code> macros right before you use them, and <code>#undef<\/code> them right after.<\/li>\n<li>Do not just <code>#undef<\/code> an existing macro before replacing it with your own; instead, pick a name that&#8217;s likely to be unique.<\/li>\n<li>Try not to use macros that expand to unbalanced C++ constructs, or at least document that behavior well.<\/li>\n<li>Prefer not using <code>##<\/code> to generate function\/class\/variable names.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"0_and_NULL\" name=\"0_and_NULL\">0 and NULL<\/a><\/h3>\n<p><span id=\"link-0_and_NULL__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=0_and_NULL#0_and_NULL\">link <\/a><\/span><span id=\"0_and_NULL__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('0_and_NULL__body','0_and_NULL__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use <code>0<\/code> for integers, <code>0.0<\/code> for reals, <code>NULL<\/code> for pointers, and <code>'\\0'<\/code> for chars.<\/div>\n<div>\n<div id=\"0_and_NULL__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Use <code>0<\/code> for integers and <code>0.0<\/code> for reals. This is not controversial.<\/p>\n<p>For pointers (address values), there is a choice between <code>0<\/code> and <code>NULL<\/code>. Bjarne Stroustrup prefers an unadorned <code>0<\/code>. We prefer <code>NULL<\/code> because it looks like a pointer. In fact, some C++ compilers, such as gcc 4.1.0, provide special definitions of <code>NULL<\/code> which enable them to give useful warnings, particularly in situations where <code>sizeof(NULL)<\/code> is not equal to <code>sizeof(0)<\/code>.<\/p>\n<p>Use <code>'\\0'<\/code> for chars. This is the correct type and also makes code more readable.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"sizeof\" name=\"sizeof\">sizeof<\/a><\/h3>\n<p><span id=\"link-sizeof__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=sizeof#sizeof\">link <\/a><\/span><span id=\"sizeof__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('sizeof__body','sizeof__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use <code>sizeof(<var>varname<\/var>)<\/code> instead of <code>sizeof(<var>type<\/var>)<\/code> whenever possible.<\/div>\n<div>\n<div id=\"sizeof__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Use <code>sizeof(<var>varname<\/var>)<\/code> because it will update appropriately if the type of the variable changes. <code>sizeof(<var>type<\/var>)<\/code> may make sense in some cases, but should generally be avoided because it can fall out of sync if the variable&#8217;s type changes.<\/p>\n<div>\n<pre>Struct data;\r\nmemset(&amp;data, 0, sizeof(data));<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">memset(&amp;data, 0, sizeof(Struct));<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Boost\" name=\"Boost\">Boost<\/a><\/h3>\n<p><span id=\"link-Boost__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Boost#Boost\">link <\/a><\/span><span id=\"Boost__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Boost__body','Boost__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use only approved libraries from the Boost library collection.<\/div>\n<div>\n<div id=\"Boost__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>The <a href=\"http:\/\/www.boost.org\/\">Boost library collection<\/a> is a popular collection of peer-reviewed, free, open-source C++ libraries.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Boost code is generally very high-quality, is widely portable, and fills many important gaps in the C++ standard library, such as type traits, better binders, and better smart pointers. It also provides an implementation of the TR1 extension to the standard library.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Some Boost libraries encourage coding practices which can hamper readability, such as metaprogramming and other advanced template techniques, and an excessively &#8220;functional&#8221; style of programming.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<div>In order to maintain a high level of readability for all contributors who might read and maintain code, we only allow an approved subset of Boost features. Currently, the following libraries are permitted:<\/p>\n<ul>\n<li><a href=\"http:\/\/www.boost.org\/libs\/utility\/call_traits.htm\">Call Traits<\/a> from <code>boost\/call_traits.hpp<\/code><\/li>\n<li><a href=\"http:\/\/www.boost.org\/libs\/utility\/compressed_pair.htm\">Compressed Pair<\/a> from <code>boost\/compressed_pair.hpp<\/code><\/li>\n<li><a href=\"http:\/\/www.boost.org\/libs\/ptr_container\/\">Pointer Container<\/a> from <code>boost\/ptr_container<\/code> except serialization and wrappers for containers not in the C++03 standard (<code>ptr_circular_buffer.hpp<\/code> and <code>ptr_unordered*<\/code>)<\/li>\n<li><a href=\"http:\/\/www.boost.org\/libs\/array\/\">Array<\/a> from <code>boost\/array.hpp<\/code><\/li>\n<li><a href=\"http:\/\/www.boost.org\/libs\/graph\/\">The Boost Graph Library (BGL)<\/a> from <code>boost\/graph<\/code>, except serialization (<code>adj_list_serialize.hpp<\/code>) and parallel\/distributed algorithms and data structures (<code>boost\/graph\/parallel\/*<\/code> and <code>boost\/graph\/distributed\/*<\/code>).<\/li>\n<li><a href=\"http:\/\/www.boost.org\/libs\/property_map\/\">Property Map<\/a> from <code>boost\/property_map<\/code>, except parallel\/distributed property maps (<code>boost\/property_map\/parallel\/*<\/code>).<\/li>\n<li>The part of <a href=\"http:\/\/www.boost.org\/libs\/iterator\/\">Iterator<\/a> that deals with defining iterators: <code>boost\/iterator\/iterator_adaptor.hpp<\/code>, <code>boost\/iterator\/iterator_facade.hpp<\/code>, and <code>boost\/function_output_iterator.hpp<\/code><\/li>\n<\/ul>\n<p>We are actively considering adding other Boost features to the list, so this rule may be relaxed in the future.<\/p><\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"C++0x\" name=\"C++0x\">C++0x<\/a><\/h3>\n<p><span id=\"link-C++0x__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=C++0x#C++0x\">link <\/a><\/span><span id=\"C++0x__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('C++0x__body','C++0x__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use only approved libraries and language extensions from C++0x. Currently, none are approved.<\/div>\n<div>\n<div id=\"C++0x__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_section\">Definition: <\/span>C++0x is the next ISO C++ standard, currently in <a href=\"http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2010\/n3092.pdf\">final committee draft<\/a> form. It contains <a href=\"http:\/\/en.wikipedia.org\/wiki\/C%2B%2B0x\">significant changes<\/a> both to the language and libraries.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>We expect that C++0x will become the next standard, and eventually will be supported by most C++ compilers. It standardizes some common C++ extensions that we use already, allows shorthands for some operations, and has some safety improvements.<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span><\/p>\n<p>The C++0x standard is substantialy more complex than its predecessor (1,300 pages versus 800 pages), and is unfamilar to many developers. The long-term effects of some features on code readability and maintenance are unknown. We cannot predict when its various features will be implemented uniformly by tools that may be of interest (gcc, icc, clang, Eclipse, etc.).<\/p>\n<p>As with <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Boost\">Boost<\/a>, some C++0x extensions encourage coding practices that hamper readability\u2014for example by removing checked redundancy (such as type names) that may be helpful to readers, or by encouraging template metaprogramming. Other extensions duplicate functionality available through existing mechanisms, which may lead to confusion and conversion costs.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span>Use only C++0x libraries and language features that have been approved for use. Currently, no such features are approved. Features will be approved individually as appropriate.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Naming\">Naming<\/h2>\n<p>The most important consistency rules are those that govern naming. The style of a name immediately informs us what sort of thing the named entity is: a type, a variable, a function, a constant, a macro, etc., without requiring us to search for the declaration of that entity. The pattern-matching engine in our brains relies a great deal on these naming rules.<\/p>\n<p>Naming rules are pretty arbitrary, but we feel that consistency is more important than individual preferences in this area, so regardless of whether you find them sensible or not, the rules are the rules.<\/p>\n<div>\n<h3><a id=\"General_Naming_Rules\" name=\"General_Naming_Rules\">General Naming Rules<\/a><\/h3>\n<p><span id=\"link-General_Naming_Rules__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=General_Naming_Rules#General_Naming_Rules\">link <\/a><\/span><span id=\"General_Naming_Rules__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('General_Naming_Rules__body','General_Naming_Rules__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Function names, variable names, and filenames should be descriptive; eschew abbreviation. Types and variables should be nouns, while functions should be &#8220;command&#8221; verbs.<\/div>\n<div>\n<div id=\"General_Naming_Rules__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">How to Name<\/span><\/p>\n<p>Give as descriptive a name as possible, within reason. Do not worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. Examples of well-chosen names:<\/p>\n<div>\n<pre>int num_errors;                  \/\/ Good.\r\nint num_completed_connections;   \/\/ Good.<\/pre>\n<\/div>\n<p>Poorly-chosen names use ambiguous abbreviations or arbitrary characters that do not convey meaning:<\/p>\n<div>\n<pre class=\"badcode\">int n;                           \/\/ Bad - meaningless.\r\nint nerr;                        \/\/ Bad - ambiguous abbreviation.\r\nint n_comp_conns;                \/\/ Bad - ambiguous abbreviation.<\/pre>\n<\/div>\n<p>Type and variable names should typically be nouns: e.g., <code>FileOpener<\/code>, <code>num_errors<\/code>.<\/p>\n<p>Function names should typically be imperative (that is they should be commands): e.g., <code>OpenFile()<\/code>, <code>set_num_errors()<\/code>. There is an exception for accessors, which, described more completely in <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Function_Names\">Function Names<\/a>, should be named the same as the variable they access.<\/p>\n<p><span class=\"stylepoint_subsection\">Abbreviations<\/span><\/p>\n<p>Do not use abbreviations unless they are extremely well known outside your project. For example:<\/p>\n<div>\n<pre>\/\/ Good\r\n\/\/ These show proper names with no abbreviations.\r\nint num_dns_connections;  \/\/ Most people know what \"DNS\" stands for.\r\nint price_count_reader;   \/\/ OK, price count. Makes sense.<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">\/\/ Bad!\r\n\/\/ Abbreviations can be confusing or ambiguous outside a small group.\r\nint wgc_connections;  \/\/ Only your group knows what this stands for.\r\nint pc_reader;        \/\/ Lots of things can be abbreviated \"pc\".<\/pre>\n<\/div>\n<p>Never abbreviate by leaving out letters:<\/p>\n<div>\n<pre>int error_count;  \/\/ Good.<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">int error_cnt;    \/\/ Bad.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"File_Names\" name=\"File_Names\">File Names<\/a><\/h3>\n<p><span id=\"link-File_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=File_Names#File_Names\">link <\/a><\/span><span id=\"File_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('File_Names__body','File_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Filenames should be all lowercase and can include underscores (<code>_<\/code>) or dashes (<code>-<\/code>). Follow the convention that your project uses. If there is no consistent local pattern to follow, prefer &#8220;_&#8221;.<\/div>\n<div>\n<div id=\"File_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Examples of acceptable file names:<\/p>\n<p><code>my_useful_class.cc<br \/>\nmy-useful-class.cc<br \/>\nmyusefulclass.cc<br \/>\nmyusefulclass_test.cc \/\/ _unittest and _regtest are deprecated.<br \/>\n<\/code><\/p>\n<p>C++ files should end in <code>.cc<\/code> and header files should end in <code>.h<\/code>.<\/p>\n<p>Do not use filenames that already exist in <code>\/usr\/include<\/code>, such as <code>db.h<\/code>.<\/p>\n<p>In general, make your filenames very specific. For example, use <code>http_server_logs.h<\/code> rather than <code>logs.h<\/code>. A very common case is to have a pair of files called, e.g., <code>foo_bar.h<\/code> and <code>foo_bar.cc<\/code>, defining a class called <code>FooBar<\/code>.<\/p>\n<p>Inline functions must be in a <code>.h<\/code> file. If your inline functions are very short, they should go directly into your <code>.h<\/code> file. However, if your inline functions include a lot of code, they may go into a third file that ends in <code>-inl.h<\/code>. In a class with a lot of inline code, your class could have three files:<\/p>\n<div>\n<pre>url_table.h      \/\/ The class declaration.\r\nurl_table.cc     \/\/ The class definition.\r\nurl_table-inl.h  \/\/ Inline functions that include lots of code.<\/pre>\n<\/div>\n<p>See also the section <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#The_-inl.h_Files\">-inl.h Files<\/a><\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Type_Names\" name=\"Type_Names\">Type Names<\/a><\/h3>\n<p><span id=\"link-Type_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Type_Names#Type_Names\">link <\/a><\/span><span id=\"Type_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Type_Names__body','Type_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Type names start with a capital letter and have a capital letter for each new word, with no underscores: <code>MyExcitingClass<\/code>, <code>MyExcitingEnum<\/code>.<\/div>\n<div>\n<div id=\"Type_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>The names of all types \u2014 classes, structs, typedefs, and enums \u2014 have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example:<\/p>\n<div>\n<pre>\/\/ classes and structs\r\nclass UrlTable { ...\r\nclass UrlTableTester { ...\r\nstruct UrlTableProperties { ...\r\n\r\n\/\/ typedefs\r\ntypedef hash_map&lt;UrlTableProperties *, string&gt; PropertiesMap;\r\n\r\n\/\/ enums\r\nenum UrlTableErrors { ...<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Variable_Names\" name=\"Variable_Names\">Variable Names<\/a><\/h3>\n<p><span id=\"link-Variable_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Variable_Names#Variable_Names\">link <\/a><\/span><span id=\"Variable_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Variable_Names__body','Variable_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Variable names are all lowercase, with underscores between words. Class member variables have trailing underscores. For instance: <code>my_exciting_local_variable<\/code>, <code>my_exciting_member_variable_<\/code>.<\/div>\n<div>\n<div id=\"Variable_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">Common Variable names<\/span><\/p>\n<p>For example:<\/p>\n<div>\n<pre>string table_name;  \/\/ OK - uses underscore.\r\nstring tablename;   \/\/ OK - all lowercase.<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">string tableName;   \/\/ Bad - mixed case.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Class Data Members<\/span><\/p>\n<p>Data members (also called instance variables or member variables) are lowercase with optional underscores like regular variable names, but always end with a trailing underscore.<\/p>\n<div>\n<pre>string table_name_;  \/\/ OK - underscore at end.\r\nstring tablename_;   \/\/ OK.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Struct Variables<\/span><\/p>\n<p>Data members in structs should be named like regular variables without the trailing underscores that data members in classes have.<\/p>\n<div>\n<pre>struct UrlTableProperties {\r\n  string name;\r\n  int num_entries;\r\n}<\/pre>\n<\/div>\n<p>See <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Structs_vs._Classes\">Structs vs. Classes<\/a> for a discussion of when to use a struct versus a class.<\/p>\n<p><span class=\"stylepoint_subsection\">Global Variables<\/span><\/p>\n<p>There are no special requirements for global variables, which should be rare in any case, but if you use one, consider prefixing it with <code>g_<\/code> or some other marker to easily distinguish it from local variables.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Constant_Names\" name=\"Constant_Names\">Constant Names<\/a><\/h3>\n<p><span id=\"link-Constant_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Constant_Names#Constant_Names\">link <\/a><\/span><span id=\"Constant_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Constant_Names__body','Constant_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use a <code>k<\/code> followed by mixed case: <code>kDaysInAWeek<\/code>.<\/div>\n<div>\n<div id=\"Constant_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>All compile-time constants, whether they are declared locally, globally, or as part of a class, follow a slightly different naming convention from other variables. Use a <code>k<\/code> followed by words with uppercase first letters:<\/p>\n<div>\n<pre>const int kDaysInAWeek = 7;<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Function_Names\" name=\"Function_Names\">Function Names<\/a><\/h3>\n<p><span id=\"link-Function_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Function_Names#Function_Names\">link <\/a><\/span><span id=\"Function_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Function_Names__body','Function_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Regular functions have mixed case; accessors and mutators match the name of the variable: <code>MyExcitingFunction()<\/code>, <code>MyExcitingMethod()<\/code>, <code>my_exciting_member_variable()<\/code>, <code>set_my_exciting_member_variable()<\/code>.<\/div>\n<div>\n<div id=\"Function_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">Regular Functions<\/span><\/p>\n<p>Functions should start with a capital letter and have a capital letter for each new word. No underscores.<\/p>\n<p>If your function crashes upon an error, you should append OrDie to the function name. This only applies to functions which could be used by production code and to errors that are reasonably likely to occur during normal operation.<\/p>\n<div>\n<pre>AddTableEntry()\r\nDeleteUrl()\r\nOpenFileOrDie()<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Accessors and Mutators<\/span><\/p>\n<p>Accessors and mutators (get and set functions) should match the name of the variable they are getting and setting. This shows an excerpt of a class whose instance variable is <code>num_entries_<\/code>.<\/p>\n<div>\n<pre>class MyClass {\r\n public:\r\n  ...\r\n  int num_entries() const { return num_entries_; }\r\n  void set_num_entries(int num_entries) { num_entries_ = num_entries; }\r\n\r\n private:\r\n  int num_entries_;\r\n};<\/pre>\n<\/div>\n<p>You may also use lowercase letters for other very short inlined functions. For example if a function were so cheap you would not cache the value if you were calling it in a loop, then lowercase naming would be acceptable.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Namespace_Names\" name=\"Namespace_Names\">Namespace Names<\/a><\/h3>\n<p><span id=\"link-Namespace_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Namespace_Names#Namespace_Names\">link <\/a><\/span><span id=\"Namespace_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Namespace_Names__body','Namespace_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Namespace names are all lower-case, and based on project names and possibly their directory structure: <code>google_awesome_project<\/code>.<\/div>\n<div>\n<div id=\"Namespace_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>See <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespaces\">Namespaces<\/a> for a discussion of namespaces and how to name them.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Enumerator_Names\" name=\"Enumerator_Names\">Enumerator Names<\/a><\/h3>\n<p><span id=\"link-Enumerator_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Enumerator_Names#Enumerator_Names\">link <\/a><\/span><span id=\"Enumerator_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Enumerator_Names__body','Enumerator_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Enumerators should be named <em>either<\/em> like <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Constant_Names\">constants<\/a> or like <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Macro_Names\">macros<\/a>: either <code>kEnumName<\/code> or <code>ENUM_NAME<\/code>.<\/div>\n<div>\n<div id=\"Enumerator_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Preferably, the individual enumerators should be named like <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Constant_Names\">constants<\/a>. However, it is also acceptable to name them like <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Macro_Names\">macros<\/a>. The enumeration name, <code>UrlTableErrors<\/code> (and <code>AlternateUrlTableErrors<\/code>), is a type, and therefore mixed case.<\/p>\n<div>\n<pre>enum UrlTableErrors {\r\n  kOK = 0,\r\n  kErrorOutOfMemory,\r\n  kErrorMalformedInput,\r\n};\r\nenum AlternateUrlTableErrors {\r\n  OK = 0,\r\n  OUT_OF_MEMORY = 1,\r\n  MALFORMED_INPUT = 2,\r\n};<\/pre>\n<\/div>\n<p>Until January 2009, the style was to name enum values like <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Macro_Names\">macros<\/a>. This caused problems with name collisions between enum values and macros. Hence, the change to prefer constant-style naming was put in place. New code should prefer constant-style naming if possible. However, there is no reason to change old code to use constant-style names, unless the old names are actually causing a compile-time problem.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Macro_Names\" name=\"Macro_Names\">Macro Names<\/a><\/h3>\n<p><span id=\"link-Macro_Names__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Macro_Names#Macro_Names\">link <\/a><\/span><span id=\"Macro_Names__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Macro_Names__body','Macro_Names__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">You&#8217;re not really going to <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Preprocessor_Macros\">define a macro<\/a>, are you? If you do, they&#8217;re like this: <code>MY_MACRO_THAT_SCARES_SMALL_CHILDREN<\/code>.<\/div>\n<div>\n<div id=\"Macro_Names__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Please see the <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Preprocessor_Macros\">description of macros<\/a>; in general macros should <em>not<\/em> be used. However, if they are absolutely needed, then they should be named with all capitals and underscores.<\/p>\n<div>\n<pre>#define ROUND(x) ...\r\n#define PI_ROUNDED 3.0<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Exceptions_to_Naming_Rules\" name=\"Exceptions_to_Naming_Rules\">Exceptions to Naming Rules<\/a><\/h3>\n<p><span id=\"link-Exceptions_to_Naming_Rules__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Exceptions_to_Naming_Rules#Exceptions_to_Naming_Rules\">link <\/a><\/span><span id=\"Exceptions_to_Naming_Rules__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Exceptions_to_Naming_Rules__body','Exceptions_to_Naming_Rules__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">If you are naming something that is analogous to an existing C or C++ entity then you can follow the existing naming convention scheme.<\/div>\n<div>\n<div id=\"Exceptions_to_Naming_Rules__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<dl>\n<dt><code>bigopen()<\/code> <\/dt>\n<dd>function name, follows form of <code>open()<\/code> <\/dd>\n<dt><code>uint<\/code> <\/dt>\n<dd><code>typedef<\/code> <\/dd>\n<dt><code>bigpos<\/code> <\/dt>\n<dd><code>struct<\/code> or <code>class<\/code>, follows form of <code>pos<\/code> <\/dd>\n<dt><code>sparse_hash_map<\/code> <\/dt>\n<dd>STL-like entity; follows STL naming conventions <\/dd>\n<dt><code>LONGLONG_MAX<\/code> <\/dt>\n<dd>a constant, as in <code>INT_MAX<\/code> <\/dd>\n<\/dl>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Comments\">Comments<\/h2>\n<p>Though a pain to write, comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names that you must then explain through comments.<\/p>\n<p>When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous \u2014 the next one may be you!<\/p>\n<div>\n<h3><a id=\"Comment_Style\" name=\"Comment_Style\">Comment Style<\/a><\/h3>\n<p><span id=\"link-Comment_Style__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Comment_Style#Comment_Style\">link <\/a><\/span><span id=\"Comment_Style__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Comment_Style__body','Comment_Style__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use either the <code>\/\/<\/code> or <code>\/* *\/<\/code> syntax, as long as you are consistent.<\/div>\n<div>\n<div id=\"Comment_Style__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>You can use either the <code>\/\/<\/code> or the <code>\/* *\/<\/code> syntax; however, <code>\/\/<\/code> is <em>much<\/em> more common. Be consistent with how you comment and what style you use where.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"File_Comments\" name=\"File_Comments\">File Comments<\/a><\/h3>\n<p><span id=\"link-File_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=File_Comments#File_Comments\">link <\/a><\/span><span id=\"File_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('File_Comments__body','File_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Start each file with a copyright notice, followed by a description of the contents of the file.<\/div>\n<div>\n<div id=\"File_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">Legal Notice and Author Line<\/span><\/p>\n<p>Every file should contain the following items, in order:<\/p>\n<ul>\n<li>a copyright statement (for example, <code>Copyright 2008 Google Inc.<\/code>)<\/li>\n<li>a license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL)<\/li>\n<li>an author line to identify the original author of the file<\/li>\n<\/ul>\n<p>\u00a0<\/p>\n<p>If you make significant changes to a file that someone else originally wrote, add yourself to the author line. This can be very helpful when another contributor has questions about the file and needs to know whom to contact about it.<\/p>\n<p><span class=\"stylepoint_subsection\">File Contents<\/span><\/p>\n<p>Every file should have a comment at the top, below the copyright notice and author line, that describes the contents of the file.<\/p>\n<p>Generally a <code>.h<\/code> file will describe the classes that are declared in the file with an overview of what they are for and how they are used. A <code>.cc<\/code> file should contain more information about implementation details or discussions of tricky algorithms. If you feel the implementation details or a discussion of the algorithms would be useful for someone reading the <code>.h<\/code>, feel free to put it there instead, but mention in the <code>.cc<\/code> that the documentation is in the <code>.h<\/code> file.<\/p>\n<p>Do not duplicate comments in both the <code>.h<\/code> and the <code>.cc<\/code>. Duplicated comments diverge.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Class_Comments\" name=\"Class_Comments\">Class Comments<\/a><\/h3>\n<p><span id=\"link-Class_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Class_Comments#Class_Comments\">link <\/a><\/span><span id=\"Class_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Class_Comments__body','Class_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Every class definition should have an accompanying comment that describes what it is for and how it should be used.<\/div>\n<div>\n<div id=\"Class_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<div>\n<pre>\/\/ Iterates over the contents of a GargantuanTable.  Sample usage:\r\n\/\/    GargantuanTableIterator* iter = table-&gt;NewIterator();\r\n\/\/    for (iter-&gt;Seek(\"foo\"); !iter-&gt;done(); iter-&gt;Next()) {\r\n\/\/      process(iter-&gt;key(), iter-&gt;value());\r\n\/\/    }\r\n\/\/    delete iter;\r\nclass GargantuanTableIterator {\r\n  ...\r\n};<\/pre>\n<\/div>\n<p>If you have already described a class in detail in the comments at the top of your file feel free to simply state &#8220;See comment at top of file for a complete description&#8221;, but be sure to have some sort of comment.<\/p>\n<p>Document the synchronization assumptions the class makes, if any. If an instance of the class can be accessed by multiple threads, take extra care to document the rules and invariants surrounding multithreaded use.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Function_Comments\" name=\"Function_Comments\">Function Comments<\/a><\/h3>\n<p><span id=\"link-Function_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Function_Comments#Function_Comments\">link <\/a><\/span><span id=\"Function_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Function_Comments__body','Function_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Declaration comments describe use of the function; comments at the definition of a function describe operation.<\/div>\n<div>\n<div id=\"Function_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">Function Declarations<\/span><\/p>\n<p>Every function declaration should have comments immediately preceding it that describe what the function does and how to use it. These comments should be descriptive (&#8220;Opens the file&#8221;) rather than imperative (&#8220;Open the file&#8221;); the comment describes the function, it does not tell the function what to do. In general, these comments do not describe how the function performs its task. Instead, that should be left to comments in the function definition.<\/p>\n<p>Types of things to mention in comments at the function declaration:<\/p>\n<ul>\n<li>What the inputs and outputs are.<\/li>\n<li>For class member functions: whether the object remembers reference arguments beyond the duration of the method call, and whether it will free them or not.<\/li>\n<li>If the function allocates memory that the caller must free.<\/li>\n<li>Whether any of the arguments can be <code>NULL<\/code>.<\/li>\n<li>If there are any performance implications of how a function is used.<\/li>\n<li>If the function is re-entrant. What are its synchronization assumptions?<\/li>\n<\/ul>\n<p>Here is an example:<\/p>\n<div>\n<pre>\/\/ Returns an iterator for this table.  It is the client's\r\n\/\/ responsibility to delete the iterator when it is done with it,\r\n\/\/ and it must not use the iterator once the GargantuanTable object\r\n\/\/ on which the iterator was created has been deleted.\r\n\/\/\r\n\/\/ The iterator is initially positioned at the beginning of the table.\r\n\/\/\r\n\/\/ This method is equivalent to:\r\n\/\/    Iterator* iter = table-&gt;NewIterator();\r\n\/\/    iter-&gt;Seek(\"\");\r\n\/\/    return iter;\r\n\/\/ If you are going to immediately seek to another place in the\r\n\/\/ returned iterator, it will be faster to use NewIterator()\r\n\/\/ and avoid the extra seek.\r\nIterator* GetIterator() const;<\/pre>\n<\/div>\n<p>However, do not be unnecessarily verbose or state the completely obvious. Notice below that it is not necessary to say &#8220;returns false otherwise&#8221; because this is implied.<\/p>\n<div>\n<pre>\/\/ Returns true if the table cannot hold any more entries.\r\nbool IsTableFull();<\/pre>\n<\/div>\n<p>When commenting constructors and destructors, remember that the person reading your code knows what constructors and destructors are for, so comments that just say something like &#8220;destroys this object&#8221; are not useful. Document what constructors do with their arguments (for example, if they take ownership of pointers), and what cleanup the destructor does. If this is trivial, just skip the comment. It is quite common for destructors not to have a header comment.<\/p>\n<p><span class=\"stylepoint_subsection\">Function Definitions<\/span><\/p>\n<p>Each function definition should have a comment describing what the function does if there&#8217;s anything tricky about how it does its job. For example, in the definition comment you might describe any coding tricks you use, give an overview of the steps you go through, or explain why you chose to implement the function in the way you did rather than using a viable alternative. For instance, you might mention why it must acquire a lock for the first half of the function but why it is not needed for the second half.<\/p>\n<p>Note you should <em>not<\/em> just repeat the comments given with the function declaration, in the <code>.h<\/code> file or wherever. It&#8217;s okay to recapitulate briefly what the function does, but the focus of the comments should be on how it does it.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Variable_Comments\" name=\"Variable_Comments\">Variable Comments<\/a><\/h3>\n<p><span id=\"link-Variable_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Variable_Comments#Variable_Comments\">link <\/a><\/span><span id=\"Variable_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Variable_Comments__body','Variable_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">In general the actual name of the variable should be descriptive enough to give a good idea of what the variable is used for. In certain cases, more comments are required.<\/div>\n<div>\n<div id=\"Variable_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">Class Data Members<\/span><\/p>\n<p>Each class data member (also called an instance variable or member variable) should have a comment describing what it is used for. If the variable can take sentinel values with special meanings, such as <code>NULL<\/code> or -1, document this. For example:<\/p>\n<div>\n<pre>private:\r\n \/\/ Keeps track of the total number of entries in the table.\r\n \/\/ Used to ensure we do not go over the limit. -1 means\r\n \/\/ that we don't yet know how many entries the table has.\r\n int num_total_entries_;<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Global Variables<\/span><\/p>\n<p>As with data members, all global variables should have a comment describing what they are and what they are used for. For example:<\/p>\n<div>\n<pre>\/\/ The total number of tests cases that we run through in this regression test.\r\nconst int kNumTestCases = 6;<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Implementation_Comments\" name=\"Implementation_Comments\">Implementation Comments<\/a><\/h3>\n<p><span id=\"link-Implementation_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Implementation_Comments#Implementation_Comments\">link <\/a><\/span><span id=\"Implementation_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Implementation_Comments__body','Implementation_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">In your implementation you should have comments in tricky, non-obvious, interesting, or important parts of your code.<\/div>\n<div>\n<div id=\"Implementation_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">Class Data Members<\/span><\/p>\n<p>Tricky or complicated code blocks should have comments before them. Example:<\/p>\n<div>\n<pre>\/\/ Divide result by two, taking into account that x\r\n\/\/ contains the carry from the add.\r\nfor (int i = 0; i &lt; result-&gt;size(); i++) {\r\n  x = (x &lt;&lt; 8) + (*result)[i];\r\n  (*result)[i] = x &gt;&gt; 1;\r\n  x &amp;= 1;\r\n}<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Line Comments<\/span><\/p>\n<p>Also, lines that are non-obvious should get a comment at the end of the line. These end-of-line comments should be separated from the code by 2 spaces. Example:<\/p>\n<div>\n<pre>\/\/ If we have enough memory, mmap the data portion too.\r\nmmap_budget = max&lt;int64&gt;(0, mmap_budget - index_-&gt;length());\r\nif (mmap_budget &gt;= data_size_ &amp;&amp; !MmapData(mmap_chunk_bytes, mlock))\r\n  return;  \/\/ Error already logged.<\/pre>\n<\/div>\n<p>Note that there are both comments that describe what the code is doing, and comments that mention that an error has already been logged when the function returns.<\/p>\n<p>If you have several comments on subsequent lines, it can often be more readable to line them up:<\/p>\n<div>\n<pre>DoSomething();                  \/\/ Comment here so the comments line up.\r\nDoSomethingElseThatIsLonger();  \/\/ Comment here so there are two spaces between\r\n                                \/\/ the code and the comment.\r\n{ \/\/ One space before comment when opening a new scope is allowed,\r\n  \/\/ thus the comment lines up with the following comments and code.\r\n  DoSomethingElse();  \/\/ Two spaces before line comments normally.\r\n}<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">NULL, true\/false, 1, 2, 3&#8230;<\/span><\/p>\n<p>When you pass in <code>NULL<\/code>, boolean, or literal integer values to functions, you should consider adding a comment about what they are, or make your code self-documenting by using constants. For example, compare:<\/p>\n<div>\n<pre class=\"badcode\">bool success = CalculateSomething(interesting_value,\r\n                                  10,\r\n                                  false,\r\n                                  NULL);  \/\/ What are these arguments??<\/pre>\n<\/div>\n<p>versus:<\/p>\n<div>\n<pre>bool success = CalculateSomething(interesting_value,\r\n                                  10,     \/\/ Default base value.\r\n                                  false,  \/\/ Not the first time we're calling this.\r\n                                  NULL);  \/\/ No callback.<\/pre>\n<\/div>\n<p>Or alternatively, constants or self-describing variables:<\/p>\n<div>\n<pre>const int kDefaultBaseValue = 10;\r\nconst bool kFirstTimeCalling = false;\r\nCallback *null_callback = NULL;\r\nbool success = CalculateSomething(interesting_value,\r\n                                  kDefaultBaseValue,\r\n                                  kFirstTimeCalling,\r\n                                  null_callback);<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Don&#8217;ts<\/span><\/p>\n<p>Note that you should <em>never<\/em> describe the code itself. Assume that the person reading the code knows C++ better than you do, even though he or she does not know what you are trying to do:<\/p>\n<div>\n<pre class=\"badcode\">\/\/ Now go through the b array and make sure that if i occurs,\r\n\/\/ the next element is i+1.\r\n...        \/\/ Geez.  What a useless comment.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Punctuation,_Spelling_and_Grammar\" name=\"Punctuation,_Spelling_and_Grammar\">Punctuation, Spelling and Grammar<\/a><\/h3>\n<p><span id=\"link-Punctuation,_Spelling_and_Grammar__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Punctuation,_Spelling_and_Grammar#Punctuation,_Spelling_and_Grammar\">link <\/a><\/span><span id=\"Punctuation,_Spelling_and_Grammar__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Punctuation,_Spelling_and_Grammar__body','Punctuation,_Spelling_and_Grammar__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones.<\/div>\n<div>\n<div id=\"Punctuation,_Spelling_and_Grammar__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Comments should usually be written as complete sentences with proper capitalization and periods at the end. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style. Complete sentences are more readable, and they provide some assurance that the comment is complete and not an unfinished thought.<\/p>\n<p>Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"TODO_Comments\" name=\"TODO_Comments\">TODO Comments<\/a><\/h3>\n<p><span id=\"link-TODO_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=TODO_Comments#TODO_Comments\">link <\/a><\/span><span id=\"TODO_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('TODO_Comments__body','TODO_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use <code>TODO<\/code> comments for code that is temporary, a short-term solution, or good-enough but not perfect.<\/div>\n<div>\n<div id=\"TODO_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><code>TODO<\/code>s should include the string <code>TODO<\/code> in all caps, followed by your name, e-mail address, or other identifier in parentheses. A colon is optional. The main purpose is to have a consistent <code>TODO<\/code> format searchable by the person adding the comment (who can provide more details upon request). A <code>TODO<\/code> is not a commitment to provide the fix yourself.<\/p>\n<div>\n<pre>\/\/ TODO(kl@gmail.com): Use a \"*\" here for concatenation operator.\r\n\/\/ TODO(Zeke) change this to use relations.<\/pre>\n<\/div>\n<p>If your <code>TODO<\/code> is of the form &#8220;At a future date do something&#8221; make sure that you either include a very specific date (&#8220;Fix by November 2005&#8221;) or a very specific event (&#8220;Remove this code when all clients can handle XML responses.&#8221;).<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Deprecation_Comments\" name=\"Deprecation_Comments\">Deprecation Comments<\/a><\/h3>\n<p><span id=\"link-Deprecation_Comments__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Deprecation_Comments#Deprecation_Comments\">link <\/a><\/span><span id=\"Deprecation_Comments__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Deprecation_Comments__body','Deprecation_Comments__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Mark deprecated interface points with <code>DEPRECATED<\/code> comments.<\/div>\n<div>\n<div id=\"Deprecation_Comments__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>You can mark an interface as deprecated by writing a comment containing the word <code>DEPRECATED<\/code> in all caps. The comment goes either before the declaration of the interface or on the same line as the declaration.<\/p>\n<p>After the word <code>DEPRECATED<\/code>, write your name, e-mail address, or other identifier in parentheses.<\/p>\n<p>A deprecation comment must include simple, clear directions for people to fix their callsites. In C++, you can implement a deprecated function as an inline function that calls the new interface point.<\/p>\n<p>Marking an interface point <code>DEPRECATED<\/code> will not magically cause any callsites to change. If you want people to actually stop using the deprecated facility, you will have to fix the callsites yourself or recruit a crew to help you.<\/p>\n<p>New code should not contain calls to deprecated interface points. Use the new interface point instead. If you cannot understand the directions, find the person who created the deprecation and ask them for help using the new interface point.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Formatting\">Formatting<\/h2>\n<p>Coding style and formatting are pretty arbitrary, but a project is much easier to follow if everyone uses the same style. Individuals may not agree with every aspect of the formatting rules, and some of the rules may take some getting used to, but it is important that all project contributors follow the style rules so that they can all read and understand everyone&#8217;s code easily.<\/p>\n<p>To help you format code correctly, we&#8217;ve created a <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/google-c-style.el\">settings file for emacs<\/a>.<\/p>\n<div>\n<h3><a id=\"Line_Length\" name=\"Line_Length\">Line Length<\/a><\/h3>\n<p><span id=\"link-Line_Length__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Line_Length#Line_Length\">link <\/a><\/span><span id=\"Line_Length__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Line_Length__body','Line_Length__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Each line of text in your code should be at most 80 characters long.<\/div>\n<div>\n<div id=\"Line_Length__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>We recognize that this rule is controversial, but so much existing code already adheres to it, and we feel that consistency is important.<\/p>\n<p><span class=\"stylepoint_section\">Pros: <\/span>Those who favor this rule argue that it is rude to force them to resize their windows and there is no need for anything longer. Some folks are used to having several code windows side-by-side, and thus don&#8217;t have room to widen their windows in any case. People set up their work environment assuming a particular maximum window width, and 80 columns has been the traditional standard. Why change it?<\/p>\n<p><span class=\"stylepoint_section\">Cons: <\/span>Proponents of change argue that a wider line can make code more readable. The 80-column limit is an hidebound throwback to 1960s mainframes; modern equipment has wide screens that can easily show longer lines.<\/p>\n<p><span class=\"stylepoint_section\">Decision: <\/span><\/p>\n<p>80 characters is the maximum.<\/p>\n<p>Exception: if a comment line contains an example command or a literal URL longer than 80 characters, that line may be longer than 80 characters for ease of cut and paste.<\/p>\n<p>Exception: an <code>#include<\/code> statement with a long path may exceed 80 columns. Try to avoid situations where this becomes necessary.<\/p>\n<p>Exception: you needn&#8217;t be concerned about <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#The__define_Guard\">header guards<\/a> that exceed the maximum length.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Non-ASCII_Characters\" name=\"Non-ASCII_Characters\">Non-ASCII Characters<\/a><\/h3>\n<p><span id=\"link-Non-ASCII_Characters__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Non-ASCII_Characters#Non-ASCII_Characters\">link <\/a><\/span><span id=\"Non-ASCII_Characters__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Non-ASCII_Characters__body','Non-ASCII_Characters__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Non-ASCII characters should be rare, and must use UTF-8 formatting.<\/div>\n<div>\n<div id=\"Non-ASCII_Characters__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>You shouldn&#8217;t hard-code user-facing text in source, even English, so use of non-ASCII characters should be rare. However, in certain cases it is appropriate to include such words in your code. For example, if your code parses data files from foreign sources, it may be appropriate to hard-code the non-ASCII string(s) used in those data files as delimiters. More commonly, unittest code (which does not need to be localized) might contain non-ASCII strings. In such cases, you should use UTF-8, since that is an encoding understood by most tools able to handle more than just ASCII. Hex encoding is also OK, and encouraged where it enhances readability \u2014 for example, <code>\"\\xEF\\xBB\\xBF\"<\/code> is the Unicode zero-width no-break space character, which would be invisible if included in the source as straight UTF-8.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Spaces_vs._Tabs\" name=\"Spaces_vs._Tabs\">Spaces vs. Tabs<\/a><\/h3>\n<p><span id=\"link-Spaces_vs._Tabs__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Spaces_vs._Tabs#Spaces_vs._Tabs\">link <\/a><\/span><span id=\"Spaces_vs._Tabs__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Spaces_vs._Tabs__body','Spaces_vs._Tabs__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use only spaces, and indent 2 spaces at a time.<\/div>\n<div>\n<div id=\"Spaces_vs._Tabs__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>We use spaces for indentation. Do not use tabs in your code. You should set your editor to emit spaces when you hit the tab key.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Function_Declarations_and_Definitions\" name=\"Function_Declarations_and_Definitions\">Function Declarations and Definitions<\/a><\/h3>\n<p><span id=\"link-Function_Declarations_and_Definitions__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Function_Declarations_and_Definitions#Function_Declarations_and_Definitions\">link <\/a><\/span><span id=\"Function_Declarations_and_Definitions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Function_Declarations_and_Definitions__body','Function_Declarations_and_Definitions__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Return type on the same line as function name, parameters on the same line if they fit.<\/div>\n<div>\n<div id=\"Function_Declarations_and_Definitions__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Functions look like this:<\/p>\n<div>\n<pre>ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {\r\n  DoSomething();\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>If you have too much text to fit on one line:<\/p>\n<div>\n<pre>ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,\r\n                                             Type par_name3) {\r\n  DoSomething();\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>or if you cannot fit even the first parameter:<\/p>\n<div>\n<pre>ReturnType LongClassName::ReallyReallyReallyLongFunctionName(\r\n    Type par_name1,  \/\/ 4 space indent\r\n    Type par_name2,\r\n    Type par_name3) {\r\n  DoSomething();  \/\/ 2 space indent\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>Some points to note:<\/p>\n<ul>\n<li>The return type is always on the same line as the function name.<\/li>\n<li>The open parenthesis is always on the same line as the function name.<\/li>\n<li>There is never a space between the function name and the open parenthesis.<\/li>\n<li>There is never a space between the parentheses and the parameters.<\/li>\n<li>The open curly brace is always at the end of the same line as the last parameter.<\/li>\n<li>The close curly brace is either on the last line by itself or (if other style rules permit) on the same line as the open curly brace.<\/li>\n<li>There should be a space between the close parenthesis and the open curly brace.<\/li>\n<li>All parameters should be named, with identical names in the declaration and implementation.<\/li>\n<li>All parameters should be aligned if possible.<\/li>\n<li>Default indentation is 2 spaces.<\/li>\n<li>Wrapped parameters have a 4 space indent.<\/li>\n<\/ul>\n<p>If your function is <code>const<\/code>, the <code>const<\/code> keyword should be on the same line as the last parameter:<\/p>\n<div>\n<pre>\/\/ Everything in this function signature fits on a single line\r\nReturnType FunctionName(Type par) const {\r\n  ...\r\n}\r\n\r\n\/\/ This function signature requires multiple lines, but\r\n\/\/ the const keyword is on the line with the last parameter.\r\nReturnType ReallyLongFunctionName(Type par1,\r\n                                  Type par2) const {\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>If some parameters are unused, comment out the variable name in the function definition:<\/p>\n<div>\n<pre>\/\/ Always have named parameters in interfaces.\r\nclass Shape {\r\n public:\r\n  virtual void Rotate(double radians) = 0;\r\n}\r\n\r\n\/\/ Always have named parameters in the declaration.\r\nclass Circle : public Shape {\r\n public:\r\n  virtual void Rotate(double radians);\r\n}\r\n\r\n\/\/ Comment out unused named parameters in definitions.\r\nvoid Circle::Rotate(double \/*radians*\/) {}<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">\/\/ Bad - if someone wants to implement later, it's not clear what the\r\n\/\/ variable means.\r\nvoid Circle::Rotate(double) {}<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Function_Calls\" name=\"Function_Calls\">Function Calls<\/a><\/h3>\n<p><span id=\"link-Function_Calls__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Function_Calls#Function_Calls\">link <\/a><\/span><span id=\"Function_Calls__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Function_Calls__body','Function_Calls__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">On one line if it fits; otherwise, wrap arguments at the parenthesis.<\/div>\n<div>\n<div id=\"Function_Calls__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Function calls have the following format:<\/p>\n<div>\n<pre>bool retval = DoSomething(argument1, argument2, argument3);<\/pre>\n<\/div>\n<p>If the arguments do not all fit on one line, they should be broken up onto multiple lines, with each subsequent line aligned with the first argument. Do not add spaces after the open paren or before the close paren:<\/p>\n<div>\n<pre>bool retval = DoSomething(averyveryveryverylongargument1,\r\n                          argument2, argument3);<\/pre>\n<\/div>\n<p>If the function has many arguments, consider having one per line if this makes the code more readable:<\/p>\n<div>\n<pre>bool retval = DoSomething(argument1,\r\n                          argument2,\r\n                          argument3,\r\n                          argument4);<\/pre>\n<\/div>\n<p>If the function signature is so long that it cannot fit within the maximum <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Line_Length\">line length<\/a>, you may place all arguments on subsequent lines:<\/p>\n<div>\n<pre>if (...) {\r\n  ...\r\n  ...\r\n  if (...) {\r\n    DoSomethingThatRequiresALongFunctionName(\r\n        very_long_argument1,  \/\/ 4 space indent\r\n        argument2,\r\n        argument3,\r\n        argument4);\r\n  }<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Conditionals\" name=\"Conditionals\">Conditionals<\/a><\/h3>\n<p><span id=\"link-Conditionals__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Conditionals#Conditionals\">link <\/a><\/span><span id=\"Conditionals__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Conditionals__body','Conditionals__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Prefer no spaces inside parentheses. The <code>else<\/code> keyword belongs on a new line.<\/div>\n<div>\n<div id=\"Conditionals__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>There are two acceptable formats for a basic conditional statement. One includes spaces between the parentheses and the condition, and one does not.<\/p>\n<p>The most common form is without spaces. Either is fine, but <em>be consistent<\/em>. If you are modifying a file, use the format that is already present. If you are writing new code, use the format that the other files in that directory or project use. If in doubt and you have no personal preference, do not add the spaces.<\/p>\n<div>\n<pre>if (condition) {  \/\/ no spaces inside parentheses\r\n  ...  \/\/ 2 space indent.\r\n} else {  \/\/ The else goes on the same line as the closing brace.\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>If you prefer you may add spaces inside the parentheses:<\/p>\n<div>\n<pre>if ( condition ) {  \/\/ spaces inside parentheses - rare\r\n  ...  \/\/ 2 space indent.\r\n} else {  \/\/ The else goes on the same line as the closing brace.\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>Note that in all cases you must have a space between the <code>if<\/code> and the open parenthesis. You must also have a space between the close parenthesis and the curly brace, if you&#8217;re using one.<\/p>\n<div>\n<pre class=\"badcode\">if(condition)     \/\/ Bad - space missing after IF.\r\nif (condition){   \/\/ Bad - space missing before {.\r\nif(condition){    \/\/ Doubly bad.<\/pre>\n<\/div>\n<div>\n<pre>if (condition) {  \/\/ Good - proper space after IF and before {.<\/pre>\n<\/div>\n<p>Short conditional statements may be written on one line if this enhances readability. You may use this only when the line is brief and the statement does not use the <code>else<\/code> clause.<\/p>\n<div>\n<pre>if (x == kFoo) return new Foo();\r\nif (x == kBar) return new Bar();<\/pre>\n<\/div>\n<p>This is not allowed when the if statement has an <code>else<\/code>:<\/p>\n<div>\n<pre class=\"badcode\">\/\/ Not allowed - IF statement on one line when there is an ELSE clause\r\nif (x) DoThis();\r\nelse DoThat();<\/pre>\n<\/div>\n<p>In general, curly braces are not required for single-line statements, but they are allowed if you like them; conditional or loop statements with complex conditions or statements may be more readable with curly braces. Some projects require that an <code>if<\/code> must always always have an accompanying brace.<\/p>\n<div>\n<pre>if (condition)\r\n  DoSomething();  \/\/ 2 space indent.\r\n\r\nif (condition) {\r\n  DoSomething();  \/\/ 2 space indent.\r\n}<\/pre>\n<\/div>\n<p>However, if one part of an <code>if<\/code>&#8211;<code>else<\/code> statement uses curly braces, the other part must too:<\/p>\n<div>\n<pre class=\"badcode\">\/\/ Not allowed - curly on IF but not ELSE\r\nif (condition) {\r\n  foo;\r\n} else\r\n  bar;\r\n\r\n\/\/ Not allowed - curly on ELSE but not IF\r\nif (condition)\r\n  foo;\r\nelse {\r\n  bar;\r\n}<\/pre>\n<\/div>\n<div>\n<pre>\/\/ Curly braces around both IF and ELSE required because\r\n\/\/ one of the clauses used braces.\r\nif (condition) {\r\n  foo;\r\n} else {\r\n  bar;\r\n}<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Loops_and_Switch_Statements\" name=\"Loops_and_Switch_Statements\">Loops and Switch Statements<\/a><\/h3>\n<p><span id=\"link-Loops_and_Switch_Statements__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Loops_and_Switch_Statements#Loops_and_Switch_Statements\">link <\/a><\/span><span id=\"Loops_and_Switch_Statements__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Loops_and_Switch_Statements__body','Loops_and_Switch_Statements__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Switch statements may use braces for blocks. Empty loop bodies should use <code>{}<\/code> or <code>continue<\/code>.<\/div>\n<div>\n<div id=\"Loops_and_Switch_Statements__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><code>case<\/code> blocks in <code>switch<\/code> statements can have curly braces or not, depending on your preference. If you do include curly braces they should be placed as shown below.<\/p>\n<p>If not conditional on an enumerated value, switch statements should always have a <code>default<\/code> case (in the case of an enumerated value, the compiler will warn you if any values are not handled). If the default case should never execute, simply <code>assert<\/code>:<\/p>\n<div>\n<pre>switch (var) {\r\n  case 0: {  \/\/ 2 space indent\r\n    ...      \/\/ 4 space indent\r\n    break;\r\n  }\r\n  case 1: {\r\n    ...\r\n    break;\r\n  }\r\n  default: {\r\n    assert(false);\r\n  }\r\n}<\/pre>\n<\/div>\n<p>Empty loop bodies should use <code>{}<\/code> or <code>continue<\/code>, but not a single semicolon.<\/p>\n<div>\n<pre>while (condition) {\r\n  \/\/ Repeat test until it returns false.\r\n}\r\nfor (int i = 0; i &lt; kSomeNumber; ++i) {}  \/\/ Good - empty body.\r\nwhile (condition) continue;  \/\/ Good - continue indicates no logic.<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">while (condition);  \/\/ Bad - looks like part of do\/while loop.<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Pointer_and_Reference_Expressions\" name=\"Pointer_and_Reference_Expressions\">Pointer and Reference Expressions<\/a><\/h3>\n<p><span id=\"link-Pointer_and_Reference_Expressions__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Pointer_and_Reference_Expressions#Pointer_and_Reference_Expressions\">link <\/a><\/span><span id=\"Pointer_and_Reference_Expressions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Pointer_and_Reference_Expressions__body','Pointer_and_Reference_Expressions__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">No spaces around period or arrow. Pointer operators do not have trailing spaces.<\/div>\n<div>\n<div id=\"Pointer_and_Reference_Expressions__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>The following are examples of correctly-formatted pointer and reference expressions:<\/p>\n<div>\n<pre>x = *p;\r\np = &amp;x;\r\nx = r.y;\r\nx = r-&gt;y;<\/pre>\n<\/div>\n<p>Note that:<\/p>\n<ul>\n<li>There are no spaces around the period or arrow when accessing a member.<\/li>\n<li>Pointer operators have no space after the <code>*<\/code> or <code>&amp;<\/code>.<\/li>\n<\/ul>\n<p>When declaring a pointer variable or argument, you may place the asterisk adjacent to either the type or to the variable name:<\/p>\n<div>\n<pre>\/\/ These are fine, space preceding.\r\nchar *c;\r\nconst string &amp;str;\r\n\r\n\/\/ These are fine, space following.\r\nchar* c;    \/\/ but remember to do \"char* c, *d, *e, ...;\"!\r\nconst string&amp; str;<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">char * c;  \/\/ Bad - spaces on both sides of *\r\nconst string &amp; str;  \/\/ Bad - spaces on both sides of &amp;<\/pre>\n<\/div>\n<p>You should do this consistently within a single file, so, when modifying an existing file, use the style in that file.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Boolean_Expressions\" name=\"Boolean_Expressions\">Boolean Expressions<\/a><\/h3>\n<p><span id=\"link-Boolean_Expressions__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Boolean_Expressions#Boolean_Expressions\">link <\/a><\/span><span id=\"Boolean_Expressions__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Boolean_Expressions__body','Boolean_Expressions__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">When you have a boolean expression that is longer than the <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Line_Length\">standard line length<\/a>, be consistent in how you break up the lines.<\/div>\n<div>\n<div id=\"Boolean_Expressions__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>In this example, the logical AND operator is always at the end of the lines:<\/p>\n<div>\n<pre>if (this_one_thing &gt; this_other_thing &amp;&amp;\r\n    a_third_thing == a_fourth_thing &amp;&amp;\r\n    yet_another &amp;&amp; last_one) {\r\n  ...\r\n}<\/pre>\n<\/div>\n<p>Note that when the code wraps in this example, both of the <code>&amp;&amp;<\/code> logical AND operators are at the end of the line. This is more common in Google code, though wrapping all operators at the beginning of the line is also allowed. Feel free to insert extra parentheses judiciously, because they can be very helpful in increasing readability when used appropriately. Also note that you should always use the punctuation operators, such as <code>&amp;&amp;<\/code> and <code>~<\/code>, rather than the word operators, such as <code>and<\/code> and <code>compl<\/code>.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Return_Values\" name=\"Return_Values\">Return Values<\/a><\/h3>\n<p><span id=\"link-Return_Values__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Return_Values#Return_Values\">link <\/a><\/span><span id=\"Return_Values__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Return_Values__body','Return_Values__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Do not needlessly surround the <code>return<\/code> expression with parentheses.<\/div>\n<div>\n<div id=\"Return_Values__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Use parentheses in <code>return expr;<\/code> only where you would use them in <code>x = expr;<\/code>.<\/p>\n<div>\n<pre>return result;                  \/\/ No parentheses in the simple case.\r\nreturn (some_long_condition &amp;&amp;  \/\/ Parentheses ok to make a complex\r\n        another_condition);     \/\/     expression more readable.<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">return (value);                \/\/ You wouldn't write var = (value);\r\nreturn(result);                \/\/ return is not a function!<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Variable_and_Array_Initialization\" name=\"Variable_and_Array_Initialization\">Variable and Array Initialization<\/a><\/h3>\n<p><span id=\"link-Variable_and_Array_Initialization__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Variable_and_Array_Initialization#Variable_and_Array_Initialization\">link <\/a><\/span><span id=\"Variable_and_Array_Initialization__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Variable_and_Array_Initialization__body','Variable_and_Array_Initialization__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Your choice of <code>=<\/code> or <code>()<\/code>.<\/div>\n<div>\n<div id=\"Variable_and_Array_Initialization__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>You may choose between <code>=<\/code> and <code>()<\/code>; the following are all correct:<\/p>\n<div>\n<pre>int x = 3;\r\nint x(3);\r\nstring name(\"Some Name\");\r\nstring name = \"Some Name\";<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Preprocessor_Directives\" name=\"Preprocessor_Directives\">Preprocessor Directives<\/a><\/h3>\n<p><span id=\"link-Preprocessor_Directives__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Preprocessor_Directives#Preprocessor_Directives\">link <\/a><\/span><span id=\"Preprocessor_Directives__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Preprocessor_Directives__body','Preprocessor_Directives__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Preprocessor directives should not be indented but should instead start at the beginning of the line.<\/div>\n<div>\n<div id=\"Preprocessor_Directives__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>Even when pre-processor directives are within the body of indented code, the directives should start at the beginning of the line.<\/p>\n<div>\n<pre>\/\/ Good - directives at beginning of line\r\n  if (lopsided_score) {\r\n#if DISASTER_PENDING      \/\/ Correct -- Starts at beginning of line\r\n    DropEverything();\r\n#endif\r\n    BackToNormal();\r\n  }<\/pre>\n<\/div>\n<div>\n<pre class=\"badcode\">\/\/ Bad - indented directives\r\n  if (lopsided_score) {\r\n    #if DISASTER_PENDING  \/\/ Wrong!  The \"#if\" should be at beginning of line\r\n    DropEverything();\r\n    #endif                \/\/ Wrong!  Do not indent \"#endif\"\r\n    BackToNormal();\r\n  }<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Class_Format\" name=\"Class_Format\">Class Format<\/a><\/h3>\n<p><span id=\"link-Class_Format__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Class_Format#Class_Format\">link <\/a><\/span><span id=\"Class_Format__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Class_Format__body','Class_Format__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Sections in <code>public<\/code>, <code>protected<\/code> and <code>private<\/code> order, each indented one space.<\/div>\n<div>\n<div id=\"Class_Format__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>The basic format for a class declaration (lacking the comments, see <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Class_Comments\">Class Comments<\/a> for a discussion of what comments are needed) is:<\/p>\n<div>\n<pre>class MyClass : public OtherClass {\r\n public:      \/\/ Note the 1 space indent!\r\n  MyClass();  \/\/ Regular 2 space indent.\r\n  explicit MyClass(int var);\r\n  ~MyClass() {}\r\n\r\n  void SomeFunction();\r\n  void SomeFunctionThatDoesNothing() {\r\n  }\r\n\r\n  void set_some_var(int var) { some_var_ = var; }\r\n  int some_var() const { return some_var_; }\r\n\r\n private:\r\n  bool SomeInternalFunction();\r\n\r\n  int some_var_;\r\n  int some_other_var_;\r\n  DISALLOW_COPY_AND_ASSIGN(MyClass);\r\n};<\/pre>\n<\/div>\n<p>Things to note:<\/p>\n<ul>\n<li>Any base class name should be on the same line as the subclass name, subject to the 80-column limit.<\/li>\n<li>The <code>public:<\/code>, <code>protected:<\/code>, and <code>private:<\/code> keywords should be indented one space.<\/li>\n<li>Except for the first instance, these keywords should be preceded by a blank line. This rule is optional in small classes.<\/li>\n<li>Do not leave a blank line after these keywords.<\/li>\n<li>The <code>public<\/code> section should be first, followed by the <code>protected<\/code> and finally the <code>private<\/code> section.<\/li>\n<li>See <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Declaration_Order\">Declaration Order<\/a> for rules on ordering declarations within each of these sections.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Constructor_Initializer_Lists\" name=\"Constructor_Initializer_Lists\">Constructor Initializer Lists<\/a><\/h3>\n<p><span id=\"link-Constructor_Initializer_Lists__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Constructor_Initializer_Lists#Constructor_Initializer_Lists\">link <\/a><\/span><span id=\"Constructor_Initializer_Lists__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Constructor_Initializer_Lists__body','Constructor_Initializer_Lists__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Constructor initializer lists can be all on one line or with subsequent lines indented four spaces.<\/div>\n<div>\n<div id=\"Constructor_Initializer_Lists__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>There are two acceptable formats for initializer lists:<\/p>\n<div>\n<pre>\/\/ When it all fits on one line:\r\nMyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {}<\/pre>\n<\/div>\n<p>or<\/p>\n<div>\n<pre>\/\/ When it requires multiple lines, indent 4 spaces, putting the colon on\r\n\/\/ the first initializer line:\r\nMyClass::MyClass(int var)\r\n    : some_var_(var),             \/\/ 4 space indent\r\n      some_other_var_(var + 1) {  \/\/ lined up\r\n  ...\r\n  DoSomething();\r\n  ...\r\n}<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Namespace_Formatting\" name=\"Namespace_Formatting\">Namespace Formatting<\/a><\/h3>\n<p><span id=\"link-Namespace_Formatting__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Namespace_Formatting#Namespace_Formatting\">link <\/a><\/span><span id=\"Namespace_Formatting__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Namespace_Formatting__body','Namespace_Formatting__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">The contents of namespaces are not indented.<\/div>\n<div>\n<div id=\"Namespace_Formatting__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Namespaces\">Namespaces<\/a> do not add an extra level of indentation. For example, use:<\/p>\n<div>\n<pre>namespace {\r\n\r\nvoid foo() {  \/\/ Correct.  No extra indentation within namespace.\r\n  ...\r\n}\r\n\r\n}  \/\/ namespace<\/pre>\n<\/div>\n<p>Do not indent within a namespace:<\/p>\n<div>\n<pre class=\"badcode\">namespace {\r\n\r\n  \/\/ Wrong.  Indented when it should not be.\r\n  void foo() {\r\n    ...\r\n  }\r\n\r\n}  \/\/ namespace<\/pre>\n<\/div>\n<p>When declaring nested namespaces, put each namespace on its own line.<\/p>\n<div>\n<pre>namespace foo {\r\nnamespace bar {<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Horizontal_Whitespace\" name=\"Horizontal_Whitespace\">Horizontal Whitespace<\/a><\/h3>\n<p><span id=\"link-Horizontal_Whitespace__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Horizontal_Whitespace#Horizontal_Whitespace\">link <\/a><\/span><span id=\"Horizontal_Whitespace__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Horizontal_Whitespace__body','Horizontal_Whitespace__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Use of horizontal whitespace depends on location. Never put trailing whitespace at the end of a line.<\/div>\n<div>\n<div id=\"Horizontal_Whitespace__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p><span class=\"stylepoint_subsection\">General<\/span><\/p>\n<div>\n<pre>void f(bool b) {  \/\/ Open braces should always have a space before them.\r\n  ...\r\nint i = 0;  \/\/ Semicolons usually have no space before them.\r\nint x[] = { 0 };  \/\/ Spaces inside braces for array initialization are\r\nint x[] = {0};    \/\/ optional.  If you use them, put them on both sides!\r\n\/\/ Spaces around the colon in inheritance and initializer lists.\r\nclass Foo : public Bar {\r\n public:\r\n  \/\/ For inline function implementations, put spaces between the braces\r\n  \/\/ and the implementation itself.\r\n  Foo(int b) : Bar(), baz_(b) {}  \/\/ No spaces inside empty braces.\r\n  void Reset() { baz_ = 0; }  \/\/ Spaces separating braces from implementation.\r\n  ...<\/pre>\n<\/div>\n<p>Adding trailing whitespace can cause extra work for others editing the same file, when they merge, as can removing existing trailing whitespace. So: Don&#8217;t introduce trailing whitespace. Remove it if you&#8217;re already changing that line, or do it in a separate clean-up operation (preferably when no-one else is working on the file).<\/p>\n<p><span class=\"stylepoint_subsection\">Loops and Conditionals<\/span><\/p>\n<div>\n<pre>if (b) {          \/\/ Space after the keyword in conditions and loops.\r\n} else {          \/\/ Spaces around else.\r\n}\r\nwhile (test) {}   \/\/ There is usually no space inside parentheses.\r\nswitch (i) {\r\nfor (int i = 0; i &lt; 5; ++i) {\r\nswitch ( i ) {    \/\/ Loops and conditions may have spaces inside\r\nif ( test ) {     \/\/ parentheses, but this is rare.  Be consistent.\r\nfor ( int i = 0; i &lt; 5; ++i ) {\r\nfor ( ; i &lt; 5 ; ++i) {  \/\/ For loops always have a space after the\r\n  ...                   \/\/ semicolon, and may have a space before the\r\n                        \/\/ semicolon.\r\nswitch (i) {\r\n  case 1:         \/\/ No space before colon in a switch case.\r\n    ...\r\n  case 2: break;  \/\/ Use a space after a colon if there's code after it.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Operators<\/span><\/p>\n<div>\n<pre>x = 0;              \/\/ Assignment operators always have spaces around\r\n                    \/\/ them.\r\nx = -5;             \/\/ No spaces separating unary operators and their\r\n++x;                \/\/ arguments.\r\nif (x &amp;&amp; !y)\r\n  ...\r\nv = w * x + y \/ z;  \/\/ Binary operators usually have spaces around them,\r\nv = w*x + y\/z;      \/\/ but it's okay to remove spaces around factors.\r\nv = w * (x + z);    \/\/ Parentheses should have no spaces inside them.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<p><span class=\"stylepoint_subsection\">Templates and Casts<\/span><\/p>\n<div>\n<pre>vector&lt;string&gt; x;           \/\/ No spaces inside the angle\r\ny = static_cast&lt;char*&gt;(x);  \/\/ brackets (&lt; and &gt;), before\r\n                            \/\/ &lt;, or between &gt;( in a cast.\r\nvector&lt;char *&gt; x;           \/\/ Spaces between type and pointer are\r\n                            \/\/ okay, but be consistent.\r\nset&lt;list&lt;string&gt; &gt; x;       \/\/ C++ requires a space in &gt; &gt;.\r\nset&lt; list&lt;string&gt; &gt; x;      \/\/ You may optionally use\r\n                            \/\/ symmetric spacing in &lt; &lt;.<\/pre>\n<\/div>\n<p>\u00a0<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Vertical_Whitespace\" name=\"Vertical_Whitespace\">Vertical Whitespace<\/a><\/h3>\n<p><span id=\"link-Vertical_Whitespace__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Vertical_Whitespace#Vertical_Whitespace\">link <\/a><\/span><span id=\"Vertical_Whitespace__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Vertical_Whitespace__body','Vertical_Whitespace__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Minimize use of vertical whitespace.<\/div>\n<div>\n<div id=\"Vertical_Whitespace__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>This is more a principle than a rule: don&#8217;t use blank lines when you don&#8217;t have to. In particular, don&#8217;t put more than one or two blank lines between functions, resist starting functions with a blank line, don&#8217;t end functions with a blank line, and be discriminating with your use of blank lines inside functions.<\/p>\n<p>The basic principle is: The more code that fits on one screen, the easier it is to follow and understand the control flow of the program. Of course, readability can suffer from code being too dense as well as too spread out, so use your judgement. But in general, minimize use of vertical whitespace.<\/p>\n<p>Some rules of thumb to help when blank lines may be useful:<\/p>\n<ul>\n<li>Blank lines at the beginning or end of a function very rarely help readability.<\/li>\n<li>Blank lines inside a chain of if-else blocks may well help readability.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h2 id=\"Exceptions_to_the_Rules\">Exceptions to the Rules<\/h2>\n<p>The coding conventions described above are mandatory. However, like all good rules, these sometimes have exceptions, which we discuss here.<\/p>\n<div>\n<h3><a id=\"Existing_Non-conformant_Code\" name=\"Existing_Non-conformant_Code\">Existing Non-conformant Code<\/a><\/h3>\n<p><span id=\"link-Existing_Non-conformant_Code__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Existing_Non-conformant_Code#Existing_Non-conformant_Code\">link <\/a><\/span><span id=\"Existing_Non-conformant_Code__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Existing_Non-conformant_Code__body','Existing_Non-conformant_Code__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">You may diverge from the rules when dealing with code that does not conform to this style guide.<\/div>\n<div>\n<div id=\"Existing_Non-conformant_Code__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>If you find yourself modifying code that was written to specifications other than those presented by this guide, you may have to diverge from these rules in order to stay consistent with the local conventions in that code. If you are in doubt about how to do this, ask the original author or the person currently responsible for the code. Remember that <em>consistency<\/em> includes local consistency, too.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div>\n<h3><a id=\"Windows_Code\" name=\"Windows_Code\">Windows Code<\/a><\/h3>\n<p><span id=\"link-Windows_Code__button\" class=\"link_button\" style=\"display: none;\"><a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml?showone=Windows_Code#Windows_Code\">link <\/a><\/span><span id=\"Windows_Code__button\" class=\"showhide_button\" onclick=\"javascript:ShowHideByName('Windows_Code__body','Windows_Code__button')\">\u25b6<\/span><\/p>\n<div style=\"display: inline;\">Windows programmers have developed their own set of coding conventions, mainly derived from the conventions in Windows headers and other Microsoft code. We want to make it easy for anyone to understand your code, so we have a single set of guidelines for everyone writing C++ on any platform.<\/div>\n<div>\n<div id=\"Windows_Code__body\" class=\"stylepoint_body\" style=\"display: none;\">\n<p>It is worth reiterating a few of the guidelines that you might forget if you are used to the prevalent Windows style:<\/p>\n<ul>\n<li>Do not use Hungarian notation (for example, naming an integer <code>iNum<\/code>). Use the Google naming conventions, including the <code>.cc<\/code> extension for source files.<\/li>\n<li>Windows defines many of its own synonyms for primitive types, such as <code>DWORD<\/code>, <code>HANDLE<\/code>, etc. It is perfectly acceptable, and encouraged, that you use these types when calling Windows API functions. Even so, keep as close as you can to the underlying C++ types. For example, use <code>const TCHAR *<\/code> instead of <code>LPCTSTR<\/code>.<\/li>\n<li>When compiling with Microsoft Visual C++, set the compiler to warning level 3 or higher, and treat all warnings as errors.<\/li>\n<li>Do not use <code>#pragma once<\/code>; instead use the standard Google include guards. The path in the include guards should be relative to the top of your project tree.<\/li>\n<li>In fact, do not use any nonstandard extensions, like <code>#pragma<\/code> and <code>__declspec<\/code>, unless you absolutely must. Using <code>__declspec(dllimport)<\/code> and <code>__declspec(dllexport)<\/code> is allowed; however, you must use them through macros such as <code>DLLIMPORT<\/code> and <code>DLLEXPORT<\/code>, so that someone can easily disable the extensions if they share the code.<\/li>\n<\/ul>\n<p>However, there are just a few rules that we occasionally need to break on Windows:<\/p>\n<ul>\n<li>Normally we <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml#Multiple_Inheritance\">forbid the use of multiple implementation inheritance<\/a>; however, it is required when using COM and some ATL\/WTL classes. You may use multiple implementation inheritance to implement COM or ATL\/WTL classes and interfaces.<\/li>\n<li>Although you should not use exceptions in your own code, they are used extensively in the ATL and some STLs, including the one that comes with Visual C++. When using the ATL, you should define <code>_ATL_NO_EXCEPTIONS<\/code> to disable exceptions. You should investigate whether you can also disable exceptions in your STL, but if not, it is OK to turn on exceptions in the compiler. (Note that this is only to get the STL to compile. You should still not write exception handling code yourself.)<\/li>\n<li>The usual way of working with precompiled headers is to include a header file at the top of each source file, typically with a name like <code>StdAfx.h<\/code> or <code>precompile.h<\/code>. To make your code easier to share with other projects, avoid including this file explicitly (except in <code>precompile.cc<\/code>), and use the <code>\/FI<\/code> compiler option to include the file automatically.<\/li>\n<li>Resource headers, which are usually named <code>resource.h<\/code> and contain only macros, do not need to conform to these style guidelines.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<h2>Parting Words<\/h2>\n<p>Use common sense and <em>BE CONSISTENT<\/em>.<\/p>\n<p>If you are editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around their <code>if<\/code> clauses, you should, too. If their comments have little boxes of stars around them, make your comments have little boxes of stars around them too.<\/p>\n<p>The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you are saying, rather than on how you are saying it. We present global style rules here so people know the vocabulary. But local style is also important. If code you add to a file looks drastically different from the existing code around it, the discontinuity throws readers out of their rhythm when they go to read it. Try to avoid this.<\/p>\n<p>OK, enough writing about writing code; the code itself is much more interesting. Have fun!<\/p>\n<hr \/>\n<p>Revision 3.180<\/p>\n<address>Benjy Weinberger<br \/>\nCraig Silverstein<br \/>\nGregory Eitzmann<br \/>\nMark Mentovai<br \/>\nTashana Landray <\/address>\n<address><\/address>\n<address><\/address>\n<address>\u6765\u6e90\uff1a<a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml\">http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml<\/a><\/address>\n","protected":false},"excerpt":{"rendered":"<p>\u00a0 Table of Contents Header Files The #define Guard Head [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[24,60,373],"class_list":["post-1522","post","type-post","status-publish","format-standard","hentry","category-fromnetwork","tag-c","tag-google","tag-373"],"views":362,"_links":{"self":[{"href":"http:\/\/www.ntxz.net\/index.php?rest_route=\/wp\/v2\/posts\/1522","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.ntxz.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.ntxz.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.ntxz.net\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.ntxz.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1522"}],"version-history":[{"count":1,"href":"http:\/\/www.ntxz.net\/index.php?rest_route=\/wp\/v2\/posts\/1522\/revisions"}],"predecessor-version":[{"id":1523,"href":"http:\/\/www.ntxz.net\/index.php?rest_route=\/wp\/v2\/posts\/1522\/revisions\/1523"}],"wp:attachment":[{"href":"http:\/\/www.ntxz.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1522"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.ntxz.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1522"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.ntxz.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1522"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}