CSCI 261 Programming Concepts (C++)

Winter/Spring 2012

C++ Style Guide

"Programs must be written for people to read, and only incidentally for machines to execute." (Abelson & Sussman)

"The computer programs that are truly beautiful, useful, and profitable must be readable by people. So we ought to address them to people, not to machines." (Donald Knuth)

"You see, assholes don't care whether other people can read their code. What they love is if you have to struggle to read their pieces of dense idiotic shit. To them, punctuation, style, indentation, spacing, or comments are just not necessary. You have to be able to read it the way they wrote it and f%$#! you if you can't." (Zed Shaw)


Writing a program that "just works" isn't enough. Programs must be readable and expressive. Here is a general set of rules to follow when formatting your code.

Code Constructs

Prefer pre-increment to post-increment whenever possible. Pre-increment is potentially faster than post-increment.

count++;
++count;

Try to minimize evaluation of the same code over and over. This is aimed especially at loops.

for (int x = 0; x < 100; ++x) {
    int myVar = 3;
    // ...
}
int myVar = 3;
for (int x = 0; x < 100; ++x) {
    // ...
}

Formatting

Use camel case in identifiers.

Capitalize the first word in an identifier as follows:

Use ALL CAPS in constant identifier names.

Whitespace

Always properly indent the statements within code blocks.

if (easy) {
x = 2 + 2;
keepGoing();
}
if (easy) {
    x = 2 + 2;
    keepGoing();
}

while (true) {
x = 2 + 2;
keepGoing();
}
while (true) {
    x = 2 + 2;
    keepGoing();
}

int myFunction() {
return 0;
}
int myFunction() {
    return 0;
}

Function Names and Parentheses

Do not use spaces between function names and parentheses:

void mangle ()
void mangle()

Keywords

Always use a single space after a keyword, and before a curly brace:

if(foo){
}
if (foo) {
}

Braces

As a base rule, place the open/left curly brace on the same line as the start of the statement:

if (codec)
{
}
if (codec) {
}

Parentheses

Use parentheses to group expressions:

if (a && b || c)
if ((a && b) || c)

a + b & c
(a + b) & c

Line Breaks

if (longExpression || otherLongExpression || otherOtherLongExpression) { }
if (longExpression
    || otherLongExpression
    || otherOtherLongExpression) {
}

Variable Names

Avoid short names (such as, a, rbarr, nughdeget) whenever possible. Use single-character variable names only for counters and temporaries, where the purpose of the variable is obvious.

Declare each variable on a separate line.

string firstName = "Thom", lastName = "Yorke";
string firstName = "Thom";
string lastName = "Yorke";

Avoid abbreviations.

int a, b;
char c, d;
int height;
int width;
char nameOfThis;
char nameOfThat;

Credit: Qt Creater Coding Rules