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.
- The most important rule is: KISS (keep it short and simple). Always choose the simpler implementation option over the more complicated one. This makes maintenance a lot easier.
- Write good C++ code. That is, readable, well commented when necessary, and object-oriented.
Code Constructs
Prefer pre-increment to post-increment whenever possible. Pre-increment is potentially faster than post-increment.
Try to minimize evaluation of the same code over and over. This is aimed especially at loops.
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:
- Variable names begin with a lower case letter.
- Function names begin with a lower case letter.
- Class names begin with a capital letter.
Use ALL CAPS in const
ant identifier names.
Whitespace
- Use four spaces for indentation, no tabs.
- Use blank lines to group statements together where suited.
- Always use only one blank line.
Always properly indent the statements within code blocks.
x = 2 + 2;
keepGoing();
}
x = 2 + 2;
keepGoing();
}
x = 2 + 2;
keepGoing();
}
x = 2 + 2;
keepGoing();
}
return 0;
}
return 0;
}
Function Names and Parentheses
Do not use spaces between function names and parentheses:
Keywords
Always use a single space after a keyword, and before a curly brace:
}
}
Braces
As a base rule, place the open/left curly brace on the same line as the start of the statement:
{
}
}
Parentheses
Use parentheses to group expressions:
Line Breaks
- Keep lines shorter than 100 characters.
- Insert line breaks if necessary.
- Commas go at the end of a broken line.
- Operators start at the beginning of the new line:
|| 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 lastName = "Yorke";
Avoid abbreviations.
char c, d;
int width;
char nameOfThis;
char nameOfThat;
Credit: Qt Creater Coding Rules
© Yong Joseph Bakos