C and C++ Elements to Avoid

Table of Contents

The List of Bad Elements
No Indentation
Compiling without warnings flags
Calling variables "file"
Identifiers without underscores
Write code in Paragraphs using Empty Lines
Don't start Classes with a Lowercase Letter
Avoid Intrusive Commenting
Accessing Object Slots Directly
'^' and '$' in Regular Expressions
Magic Numbers
Mixing Tabs and Spaces
Several synchronised arrays.
Modifying data structures while iterating through them.
Comments and Identifiers in a Foreign Language
“using namespace std;”
The Law of Demeter
Passing parameters in delegation
Duplicate Code
Long Functions and Methods
Using the ternary operator for side-effects instead of if/else
Using Global Variables as an Interface to the Module
Using Global Variables or Function-"static" Variables
Declaring all variables at the top (Pre-declarations)
Trailing Whitespace
Code and Markup Injection
Using Undeclared Symbols
Declarations not in common headers
Headers without #include guards or #pragma once
Overly Long Lines in the Source Code
Regular Expressions starting or ending with “.*”
Populating a Data Structure with Multiple Copies of the Same Pointer or Reference
Using One Variable for Two (or More) Different Purposes
Premature Optimisation
Not Using Version Control
Writing Automated Tests
Parsing XML/HTML/JSON/CSV/etc. without a tried-and-tested parser
Generating invalid Markup (of HTML/etc.)
Capturing Instead of Clustering in Regular Expressions
Buffer Overflows
Format String Vulnerabilities (printf/etc.)
Callbacks that do not accept a “void *” context variable
Not Using a Proper Build System
Not Using a Bug Tracker/Issue Tracker
Sources of This Advice


Often when people ask for help with C or C++ code, they show code that suffers from many bad or outdated elements. This is expected, as there are many bad tutorials out there, and lots of bad code that people have learned from, but it is still not desirable. To encourage best practices, here is a document of some of the common bad elements that people tend to use and some better practices that should be used instead.

A book I read said, that as opposed to most previous idea systems, they were trying to liquidate negatives instead of to instil positives in people. So in the spirit of liquidating negatives, this tutorial-in-reverse aims to show you what not to do.

Note: Please don't think this advice is meant as gospel. There are some instances where one can expect to deviate from it, and a lot of it can be considered only the opinion of its originators. I tried to filter the various pieces of advice I found in the sources and get rid of things that are either a matter of taste, or not so critical, or that have arguments for and against (so-called colour of the bike shed arguments), but some of the advice here may still be controversial.