<p>What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people <em>insist</em> that every <code>if</code> statement is followed by a brace block (<code>{...}</code>).</p>

<p>I'm interested in what guidelines other people follow, and the reasons behind them. I'm also interested in guidelines that you think are rubbish, but are commonly held. Can anyone suggest a few?</p>

<p>To get the ball rolling, I'll mention a few to start with:</p>

<ul>
<li>Always use braces after every <code>if</code> / <code>else</code> statement (mentioned above). The rationale behind this is that it's not always easy to tell if a single statement is actually one statement, or a preprocessor macro that expands to more than one statement, so this code would break:</li>
</ul>

<pre>
    // top of file:
    #define statement doSomething(); doSomethingElse

    // in implementation:
    if (somecondition)
        doSomething();
</pre>

<p>but if you use braces then it will work as expected.</p>

<ul>
<li>Use preprocessor macros for conditional compilation ONLY. preprocessor macros can cause all sorts of hell, since they don't allow C++ scoping rules. I've run aground many times due to preprocessor macros with common names in header files. If you're not careful you can cause all sorts of havoc!</li>
</ul>

<p>Now over to you.</p>

[{'answer_id': 60682, 'author': 'DShook', 'author_id': 370, 'author_profile': 'https://Stackoverflow.com/users/370', 'pm_score': 0, 'selected': False, 'text': '<p>make sure you indent properly</p>\n'}, {'answer_id': 60687, 'author': 'MP24', 'author_id': 6206, 'author_profile': 'https://Stackoverflow.com/users/6206', 'pm_score': 3, 'selected': False, 'text': '<ul>\n<li>Use and enforce a common coding style and guidelines. <em>Rationale:</em> Every developer on the team or in the firm is able to read the code without distractions that may occur due to different brace styles or similar.</li>\n<li>Regularly do a full rebuild of your entire source base (i.e. do daily builds or builds after each checkin) and report any errors! <em>Rationale:</em> The source is almost always in a usable state, and problems are detected shortly after they are "implemented", where problem solving is cheap.</li>\n</ul>\n'}, {'answer_id': 60712, 'author': 'David Joyner', 'author_id': 1146, 'author_profile': 'https://Stackoverflow.com/users/1146', 'pm_score': 4, 'selected': True, 'text': '<p>A few of my personal favorites:</p>\n\n<p>Strive to write code that is <a href="http://www.parashift.com/c++-faq-lite/const-correctness.html" rel="noreferrer">const correct</a>.  You will enlist the compiler to help weed out easy to fix but sometimes painful bugs.  Your code will also tell a story of what you had in mind at the time you wrote it -- valuable for newcomers or maintainers once you\'re gone.</p>\n\n<p>Get out of the memory management business.  Learn to use smart pointers: <code>std::auto_ptr</code>, <code>std::tr1::shared_ptr</code> (or <code>boost::shared_ptr</code>) and <code>boost::scoped_ptr</code>.  Learn the differences between them and when to use one vs. another.</p>\n\n<p>You\'re probably going to be using the Standard Template Library.  Read the <a href="https://rads.stackoverflow.com/amzn/click/com/0201379260" rel="noreferrer" rel="nofollow noreferrer">Josuttis book</a>.  Don\'t just stop after the first few chapters on containers thinking that you know the STL.  Push through to the good stuff: algorithms and function objects.</p>\n'}, {'answer_id': 60715, 'author': 'Brian Paden', 'author_id': 3176, 'author_profile': 'https://Stackoverflow.com/users/3176', 'pm_score': 2, 'selected': False, 'text': "<p>In if statements put the constant on the left i.e.</p>\n\n<pre><code>if( 12 == var )\n</code></pre>\n\n<p>not</p>\n\n<pre><code>if( var == 12 )\n</code></pre>\n\n<p>Beacause if you miss typing a '=' then it becomes assignment.  In the top version the compiler says this isn't possible, in the latter it runs and the if is always true.</p>\n\n<p>I use braces for if's whenever they are not on the same line.</p>\n\n<pre><code>if( a == b ) something();\nif( b == d )\n{\n    bigLongStringOfStuffThatWontFitOnASingleLineNeatly();\n}\n</code></pre>\n\n<p>Open and close braces always get their own lines.  But that is of course personal convention.</p>\n"}, {'answer_id': 60721, 'author': 'Sam Hasler', 'author_id': 2541, 'author_profile': 'https://Stackoverflow.com/users/2541', 'pm_score': 1, 'selected': False, 'text': '<p>In a similar vein you might find some useful suggestions here: <a href="https://stackoverflow.com/questions/26086/how-do-you-make-wrong-code-look-wrong-what-patterns-do-you-use-to-avoid-semanti">How do you make wrong code look wrong? What patterns do you use to avoid semantic errors?</a></p>\n'}, {'answer_id': 60733, 'author': 'Fire Lancer', 'author_id': 6266, 'author_profile': 'https://Stackoverflow.com/users/6266', 'pm_score': 1, 'selected': False, 'text': '<ul>\n<li><p>Use tabs for indentations, but align data with spaces\nThis means people can decide how much to indent by changing the tab size, but also that things stay aligned (eg you might want all the \'=\' in a vertical line when assign values to a struct)</p></li>\n<li><p>Allways use constants or inline functions instead of macros where posible</p></li>\n<li><p>Never use \'using\' in header files, because everything that includes that heafer will also be affected, even if the person includeing your header doesn\'t want all of std (for example) in their global namespace.</p></li>\n<li><p>If something is longer than about 80 columes, break it up into multiple lines eg</p>\n\n<pre><code>if(SomeVeryLongVaribleName != LongFunction(AnotherVarible, AString) &amp;&amp;\n   BigVaribleIsValid(SomeVeryLongVaribleName))\n{\n    DoSomething();\n}\n</code></pre></li>\n<li><p>Only overload operators to make them do what the user expects, eg overloading the + and - operators for a 2dVector is fine</p></li>\n<li><p>Always comment your code, even if its just to say what the next block is doing (eg "delete all textures that are not needed for this level"). Someone may need to work with it later, posibly after you have left and they don\'t want to find 1000\'s of lines of code with no comments to indicate whats doing what.</p></li>\n</ul>\n'}, {'answer_id': 60735, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 3, 'selected': False, 'text': '<ol>\n<li>Delete unnecessary code.</li>\n</ol>\n\n<p>That is all.</p>\n'}, {'answer_id': 60747, 'author': 'Rob Wells', 'author_id': 2974, 'author_profile': 'https://Stackoverflow.com/users/2974', 'pm_score': 2, 'selected': False, 'text': "<ol>\n<li>Use consistent formatting.</li>\n<li>When working on legacy code employ the existing style of formatting, esp. brace style.</li>\n<li>Get a copy of Scott Meyer's book Effective C++</li>\n<li>Get a copy of Steve MConnell's book Code Complete.</li>\n</ol>\n"}, {'answer_id': 60749, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 2, 'selected': False, 'text': "<p>Only comment when it's only necessary to explain what the code is doing, where reading the code couldn't tell you the same.</p>\n\n<p>Don't comment out code that you aren't using any more. If you want to recover old code, use your source control system.  Commenting out code just makes things look messy, and makes your comments that actually are important fade into the background mess of commented code.</p>\n"}, {'answer_id': 60773, 'author': 'Jeffrey04', 'author_id': 5742, 'author_profile': 'https://Stackoverflow.com/users/5742', 'pm_score': 1, 'selected': False, 'text': "<ol>\n<li>setup coding convention and make everyone involved follow the convention (you wouldn't want reading code that require you to figure out where is the next statement/expression because it is not indented properly)</li>\n<li>constantly refactoring your code (get a copy of Refactoring, by Martin Fowler, pros and cons are detailed in the book)</li>\n<li>write loosely coupled code (avoid writing comment by writing self-explanatory code, loosely coupled code tends to be easier to manage/adapt to change)</li>\n<li>if possible, unit test your code (or if you are macho enough, TDD.)</li>\n<li>release early, release often</li>\n<li>avoid premature optimization (profiling helps in optimizing)</li>\n</ol>\n"}, {'answer_id': 60796, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 3, 'selected': False, 'text': "<p>Turn on all the warnings you can stand in your compiler (gcc: <code>-Wall</code> is a good start but doesn't include everything so check the docs), and make them errors so you have to fix them (gcc: <code>-Werror</code>).</p>\n"}, {'answer_id': 61182, 'author': 'Thomi', 'author_id': 1304, 'author_profile': 'https://Stackoverflow.com/users/1304', 'pm_score': 0, 'selected': False, 'text': "<p>Hmm - I probably should have been a bit more specific.</p>\n\n<p>I'm not so much looking for advice for myself - I'm writing a static code analysis tool (the current commercial offerings just aren't good enough for what I want), and I'm looking for ideas for plugins to highlight possible errors in the code.</p>\n\n<p>Several people have mentioned things like const correctness and using smart pointers - that's the kind of think I can check for. Checking for indentation and commenting is a bit harder to do (from a programming point of view anyway).</p>\n"}, {'answer_id': 61187, 'author': 'macbirdie', 'author_id': 5049, 'author_profile': 'https://Stackoverflow.com/users/5049', 'pm_score': 2, 'selected': False, 'text': '<p>There is also a nice <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml" rel="nofollow noreferrer">C++ Style Guide</a> used internally by Google, which includes most of the rules mentioned here.</p>\n'}, {'answer_id': 61273, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Google\'s style guide, mentioned in one of these answers, is pretty solid.  There\'s some pointless stuff in it, but it\'s more good than bad.</p>\n\n<p>Sutter and Alexandrescu wrote a decent book on this subject, called <em>C++ Coding Standards</em>.</p>\n\n<p>Here\'s some general tips from lil\' ole me:</p>\n\n<ol>\n<li><p>Your indentation and bracketing style are both wrong.  So are everyone else\'s.  So follow the project\'s standards for this.  Swallow your pride and setup your editor so that everything is as consistent as possible with the rest of the codebase.  It\'s really really annoying having to read code that\'s indented inconsistently.  That said, bracketing and indenting have nothing whatsoever to do with "improving your code."  It\'s more about improving your ability to work with others.</p></li>\n<li><p>Comment well.  This is extremely subjective, but in general it\'s always good to write comments about <em>why</em> code works the way it does, rather than explaining what it does.  Of course for complex code it\'s also good for programmers who may not be familiar with the algorithm or code to have an idea of <em>what</em> it\'s doing as well.  Links to descriptions of the algorithms employed are very welcome.</p></li>\n<li><p>Express logic in as straightforward a manner as possible.  Ironically suggestions like "put constants on the left side of comparisons" have gone wrong here, I think.  They\'re very popular, but for English speakers, they often break the logical flow of the program to those reading.  If you can\'t trust yourself (or your compiler) to write equality compares correctly, then by all means use tricks like this.  But you\'re sacrificing clarity when you do it.  Also falling under this category are things like ... "Does my logic have 3 levels of indentation?  Could it be simpler?" and rolling similar code into functions.  Maybe even splitting up functions.  It takes experience to write code that elegantly expresses the underlying logic, but it\'s worth working at it.</p></li>\n</ol>\n\n<p>Those were pretty general.  For specific tips I can\'t do a much better job than Sutter and Alexandrescu.</p>\n'}, {'answer_id': 64902, 'author': 'Ian Hickman', 'author_id': 8915, 'author_profile': 'https://Stackoverflow.com/users/8915', 'pm_score': 1, 'selected': False, 'text': '<p>Where you can, use pre-increment instead of post-increment.</p>\n'}, {'answer_id': 64984, 'author': 'Dave', 'author_id': 9056, 'author_profile': 'https://Stackoverflow.com/users/9056', 'pm_score': 2, 'selected': False, 'text': "<p>Start to write a lot of comments -- but use that as an opportunity to refactor the code so that it's self explanatory.  </p>\n\n<p>ie:</p>\n\n<pre><code>for(int i=0; i&lt;=arr.length; i++) {\n  arr[i].conf() //confirm that every username doesn't contain invalid characters\n}\n</code></pre>\n\n<p>Should've been something more like</p>\n\n<pre><code>for(int i=0; i&lt;=activeusers.length; i++) {\n  activeusers[i].UsernameStripInvalidChars()\n}\n</code></pre>\n"}, {'answer_id': 65279, 'author': 'Trent', 'author_id': 9083, 'author_profile': 'https://Stackoverflow.com/users/9083', 'pm_score': 1, 'selected': False, 'text': '<p>I use PC-Lint on my C++ projects and especially like how it references existing publications such as the MISRA guidelines or Scott Meyers\' "Effective C++" and "More Effective C++".  Even if you are planning on writing very detailed justifications for each rule your static analysis tool checks, it is a good idea to point to established publications that your user trusts.</p>\n'}, {'answer_id': 70111, 'author': 'Stacker', 'author_id': 6574, 'author_profile': 'https://Stackoverflow.com/users/6574', 'pm_score': 1, 'selected': False, 'text': '<p>Here is the most important piece of advice I was given by a C++ guru, and it helped me in a few critical occasions to find bugs in my code:</p>\n\n<ul>\n<li>Use const methods when a method is <strong>not supposed</strong> to modify the object.</li>\n<li>Use const references and pointers in parameters when the object is <strong>not supposed</strong> to modify the object.</li>\n</ul>\n\n<p>With these 2 rules, the compiler will tell you for free where in your code the logic is flawed!</p>\n'}, {'answer_id': 70220, 'author': 'Carl Seleborg', 'author_id': 2095, 'author_profile': 'https://Stackoverflow.com/users/2095', 'pm_score': 0, 'selected': False, 'text': '<p>Smart pointers have a nice way of indicating ownership very clearly. If you\'re a class or a function:</p>\n\n<ul>\n<li>if you get a <strong>raw pointer</strong>, you don\'t own anything. You\'re allowed to use the pointee, courtesy of your caller, who guarantees that the pointee will stay alive longer than you.</li>\n<li>if you get a <strong>weak_ptr</strong>, you don\'t own the pointee, and on top of that the pointee can disappear at any time.</li>\n<li>if you get a <strong>shared_ptr</strong>, you own the object along with others, so you don\'t need to worry. Less stress, but also less control.</li>\n<li>if you get an <strong>auto_ptr</strong>, you are the sole owner of the object. It\'s yours, you\'re the king. You have the power to destroy that object, or give it to someone else (thereby losing ownership).</li>\n</ul>\n\n<p>I find the case for auto_ptr particularly strong: in a design, if I see an auto_ptr, I immediately know that that object is going to "wander" from one part of the system to the other.</p>\n\n<p>This is at least the logic I use on my pet project. I\'m not sure how many variations there can be on the topic, but until now this ruleset has served me well.</p>\n'}, {'answer_id': 70260, 'author': 'Marcin Gil', 'author_id': 5731, 'author_profile': 'https://Stackoverflow.com/users/5731', 'pm_score': 1, 'selected': False, 'text': '<p>Also, for some good techniques you might follow <a href="http://googletesting.blogspot.com/2007/01/introducing-testing-on-toilet.html" rel="nofollow noreferrer">Google\'s blog "Testing on the Toilet"</a>.</p>\n'}, {'answer_id': 181235, 'author': 'DarenW', 'author_id': 10468, 'author_profile': 'https://Stackoverflow.com/users/10468', 'pm_score': 1, 'selected': False, 'text': '<p>Look at it six months later</p>\n'}]
['https://Stackoverflow.com/questions/60673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1304/']