3. The format of the code that I used to write C + +

Source: Internet
Author: User
Tags assert function definition

Idle to have nothing to do, to use for self-C + + programming specification collation. The content comes mainly from Google and Huawei, and a little bit of Microsoft.

It is important that the entire project be subject to a unified programming style, so that everyone is easier to read and understand the code.
 
1. Line length
The number of code characters per line does not exceed 80.
Exceptions:
1) If a line of comments contains more than 80 characters of the command or URL, for the convenience of copy and paste can be more than 80 characters;
2) contains a long path can exceed 80 columns, try to avoid;
3) header File Protection can ignore this principle.
 
2. Non-ASCII characters
Try not to use non-ASCII characters, you must use the UTF-8 format when using.
Even in English, the text of the user interface should not be hard-coded into the source code, so the non-ASCII characters should be used sparingly. This type of character can be appropriately included in special cases. For example, when code parses an external data file, you can properly hardcode non-ASCII strings in the data file as delimiters, and more commonly, the unit test code (which does not need to be localized) may contain non-ASCII strings. In such cases, the UTF-8 format should be used, because many tools can understand and manipulate their encoding, and hexadecimal encoding can, especially in the case of enhanced readability-such as "\verb \XEF\XBB\XBF" is Unicode zero-width no-break The space character, contained in the UTF-8 format, is not visible in the source file.
 
3. Indent in
Use only spaces to indent 2 spaces at a time. Instead of using tabs in your code, set the editor to turn the tab into a space.
 
4. function declaration and definition
The return type and function name are on the same line, and if appropriate, the parameters are also on the same line.
The function looks like this:

ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {  DoSomething();  ...}

If you have more text on the same line, you cannot tolerate all parameters:

ReturnType ClassName::ReallyLongFunctionName(Type par_name1,                                             Type par_name2,                                             Type par_name3) {  DoSomething();  ...}

Even the first parameter will not fit:

ReturnType LongClassName::ReallyReallyReallyLongFunctionName(    Type par_name1, // 4 space indent    Type par_name2,    Type par_name3) {  DoSomething(); // 2 space indent  ...}

Note the following points:
1) The return value is always the same line as the function name;
2) The left parenthesis (open parenthesis) is always the same line as the function name;
3) There is no space between the function name and the left parenthesis;
4) There is no space between the parentheses and the parameters;
5) The left curly brace (open curly brace) is always at the end of the last parameter at the same line;
6) The closing curly brace (close curly brace) is always on the last line of the function alone;
7) There is always a space between the right parenthesis (close parenthesis) and the left curly brace;
8) All formal parameter names at function declaration and implementation must be consistent;
9) All formal parameters should be aligned as far as possible;
10) The default indentation is 2 spaces;
11) The parameters of the standalone package keep the indentation of 4 spaces.
If the function is const, the keyword const should be on the same line as the last parameter.

// Everything in this function signature fits on a single lineReturnType FunctionName(Type par) const {  ...}// This function signature requires multiple lines, but// the const keyword is on the line with the last parameter.ReturnType ReallyLongFunctionName(Type par1,                                  Type par2) const {  ...}

If some of the parameters are not used, annotate the parameter names at the function definition:

// Always have named parameters in interfaces.class Shape { public:  virtual void Rotate(double radians) = 0;}// Always have named parameters in the declaration.class Circle : public Shape { public:  virtual void Rotate(double radians);}// Comment out unused named parameters in definitions.void Circle::Rotate(double /*radians*/) {}// Bad - if someone wants to implement later, it‘s not clear what the// variable means.void Circle::Rotate(double) {}

 
5. Function call
Try to put it on the same line, or enclose the argument in parentheses.
function calls follow the following form:

bool retval = DoSomething(argument1, argument2, argument3);

If the same line does not fit, it can be broken into multiple lines, each subsequent line is aligned with the first argument, and the left parenthesis and the right parenthesis do not leave spaces before:

bool retval = DoSomething(averyveryveryverylongargument1,                          argument2, argument3);

If the function parameters are more, one parameter per line can be considered for readability:

bool retval = DoSomething(argument1,                          argument2,                          argument3,                          argument4);

If the function name is too long to exceed the maximum length of the line, you can separate all parameters into rows:

if (...) {  ...  ...  if (...) {    DoSomethingThatRequiresALongFunctionName(        very_long_argument1, // 4 space indent        argument2,        argument3,        argument4);}

 
6. Conditional statements
Do not add spaces in parentheses, the keyword else is another line.

if (condition) { // no spaces inside parentheses  ... // 2 space indent.} else { // The else goes on the same line as the closing brace.  ...}

There is a space between the IF and the left parenthesis, and a space between the right parenthesis and the left curly brace (if used):

if(condition)    // Bad - space missing after IF.if (condition){  // Bad - space missing before {.if(condition){   // Doubly bad.if (condition) { // Good - proper space after IF and before {.

Some conditional statements are written on the same line to enhance readability, and are used only when the statement is simple and does not use the ELSE clause:

if (x == kFoo) return new Foo();if (x == kBar) return new Bar();

If the statement has an else branch, it is not allowed:

// Not allowed - IF statement on one line when there is an ELSE clauseif (x) DoThis();else DoThat();

Usually, a single-line statement does not need braces, and if you prefer it is understandable, there are those who ask if the braces must be used:

if (condition)  DoSomething(); // 2 space indent.if (condition) {  DoSomething(); // 2 space indent.}

But if any of the branches in the statement use curly braces, the rest must also be used:

// Not allowed - curly on IF but not ELSEif (condition) {  foo;} else  bar;// Not allowed - curly on ELSE but not IFif (condition)  foo;else {  bar;}// Curly braces around both IF and ELSE required because// one of the clauses used braces.if (condition) {  foo;} else {  bar;}

 
7. Loop and switch selection statements
The switch statement can be chunked with braces, and the empty loop body should use {} or continue.
The case block in the switch statement can also be used without a brace, depending on your preference, as described below.
If there is a value that does not satisfy the case enumeration condition, always include a default (the compiler will alert if there is no case to handle the input value). If default is never executed, you can simply use assert:

switch (var) {  case 0: { // 2 space indent    ...     // 4 space indent    break;  }  case 1: {    ...    break;  }  default: {    assert(false);  }}

The empty loop body should use {} or continue instead of a simple semicolon:

while (condition) {  // Repeat test until it returns false.}for (int i = 0; i < kSomeNumber; ++i) {} // Good - empty body.while (condition) continue; // Good - continue indicates no logic.while (condition); // Bad - looks like part of do/while loop.

 
8. Pointers and reference expressions
Do not have spaces before or after the period (.) or arrow (.), and do not have spaces after the pointer/address operator (*, &).
The following are the correct examples of pointers and reference expressions:

x = *p;p = &x;x = r.y;x = r->y;

Note: \
1) When accessing a member, there are no spaces before and after the period or arrow;
2) There are no spaces after the pointer operator * or \&.
When you declare a pointer variable or parameter, the asterisk and the type or variable name are all close:

// These are fine, space preceding.char *c;const string &str;// These are fine, space following.char* c;    // but remember to do "char* c, *d, *e, ...;"!const string& str;char * c;   // Bad - spaces on both sides of *const string & str; // Bad - spaces on both sides of &

At a minimum, the same file (new or existing) should remain consistent.
 
9. Boolean expression
If a Boolean expression exceeds the standard line width (80 characters), if the break is to be unified.
In the following example, the logical and (\&\&) operators are always at the end of the line:

if (this_one_thing > this_other_thing &&    a_third_thing == a_fourth_thing &&    yet_another & last_one) {  ...}

Two logic and (&&) operators are located at the end of the line, you can consider the extra parenthesis, reasonable use of the words is helpful to enhance readability.
 
10. function return value
Do not use parentheses in the return expression.
Do not use parentheses when returning functions:

return x; // not return(x);

 
11. Variable and array initialization
select = or ().
To make a choice between the two, the following form is correct:

int x = 3;int x(3);string name("Some Name");string name = "Some Name";

 
12. preprocessing directives
Preprocessing directives do not indent, starting at the beginning of the line.
Even if the preprocessing directives are in the indentation code block, the instructions should start at the beginning of the line.

// Good - directives at beginning of line  if (lopsided_score) {#if DISASTER_PENDING      // Correct -- Starts at beginning of line    DropEverything();#endif    BackToNormal();  }// Bad - indented directives  if (lopsided_score) {    #if DISASTER_PENDING // Wrong! The "#if" should be at beginning ofline    DropEverything();    #endif              // Wrong! Do not indent "#endif"    BackToNormal();}

 
13. Class format
The Declaration property Order is public:, Protected:, Private: Indents 1 spaces at a time. The basic format of a class declaration is as follows:

class MyClass : public OtherClass { public:      // Note the 1 space indent!  MyClass();  // Regular 2 space indent.  explicit MyClass(int var);  ~MyClass() {}  void SomeFunction();  void SomeFunctionThatDoesNothing() {  }  void set_some_var(int var) { some_var_ = var; }  int some_var() const { return some_var_; } private:  bool SomeInternalFunction();  int some_var_;  int some_other_var_;  DISALLOW_COPY_AND_ASSIGN(MyClass);};

Attention:
1) All base class names should be in the same row as the subclass name under the 80-column limit;
2) Keywords public:, protected:, Private: to indent 1 spaces;
3) In addition to the first keyword (generally public), the other words in front of the empty line, if the analogy is smaller.
not empty;
4) These keywords should not be empty line;
5) public on the front, then protected and private;
 
14. Initialize List
The constructor initialization list is placed in the same row or indented in a few rows by four cells.
There are two acceptable initialization list formats:

// When it all fits on one line:MyClass::MyClass(int var) : some_var_(var), some_other_var_(var + 1) {

Or

// When it requires multiple lines, indent 4 spaces, putting the colon on// the first initializer line:MyClass::MyClass(int var)    : some_var_(var),    // 4 space indent      some_other_var_(var + 1) { // lined up  ...  DoSomething();  ...}

 
15. namespace formatting
Namespace content is not indented.
namespaces do not add additional indentation levels, for example:

namespace {void foo() { // Correct. No extra indentation within namespace.  ...}} // namespace

Do not indent:

namespace {  // Wrong. Indented when it should not be.  void foo() {    ...  }} // namespace

 
16. Horizontal Stay White
The use of horizontal white is adapted to local conditions. Do not add unnecessary white at the end of the line.
  Ordinary:

void f(bool b) { // 左大括号之前总是有一个空格。  ...int i = 0; // 分号前通常没有空格。int x[] = {0};   // 数组初始化时大括号内不留空格。class Foo : public Bar {  public:  // 对于内联函数实现,在大括号和实现本身之间放置空格。  Foo(int b) : Bar(), baz_(b) {} // 空括号内没有空格。  void Reset() { baz_ = 0; } // 用空格分开大括号与实现。  ...

Adding redundant white space creates additional burdens for other people to edit, so don't add extra spaces. If you are sure that a line of code has been modified, remove the extra space, or remove it when you specifically clean the space (make sure no one else is using it).
  Loop and Conditional statements:

if (b) {        // 在条件和循环的关键字之后加空格。} else {        // else左右都有空格。}while (test) {} // 圆括号内通常没有空格。switch (i) {for (int i = 0; i < 5; ++i) {switch ( i ) {  // 循环和条件可能在圆括号内有空格,但这很少见。注意保持一致。if ( test ) {for ( int i = 0; i < 5; ++i ) {for ( ; i < 5 ; ++i) { // For循环在分号后总是有一个空格,...                    // 并且在分号之前可能有一个空格。switch (i) {case 1:                // switch语句内case中的冒号前没有空格。...case 2: break;         // 如果后面有代码,则在冒号后面使用空格。

  Templates and Transformations:

vector<string> x;          // No spaces inside the angley = static_cast<char*>(x); // brackets (< and >), before                           // <, or between >( in a cast.vector<char *> x;          // Spaces between type and pointer are                           // okay, but be consistent.set<list<string> > x;      // C++ requires a space in > >.set< list<string> > x;     // You may optionally make use                           // symmetric spacing in < <.

 
17. Vertical Stay White
The less vertical the more white the better.
This is not just a rule but a matter of principle: don't use blank lines if it's not very necessary. In particular: Do not empty more than 2 lines between two function definitions, function body Head, tail do not have blank lines, the function body also do not arbitrarily add empty lines.
The basic principle is that the more code the same screen can display, the easier the control flow of the program will be understood. Of course, overly dense blocks of code and overly loose blocks of code are equally ugly, depending on your judgment, but usually the fewer the better.
function head, tail do not have blank line:

void Function() {  // Unnecessary blank lines before and after}

code block, tail do not have blank line:

while (condition) {  // Unnecessary blank line after}if (condition) {  // Unnecessary blank line before}

 
18. Supplemental provisions and instructions
More than 18.1 phrase sentences (including assignment statements) are not allowed to be written in the same line, that is, a single statement is written on one line.
  Example:
Poor typesetting:

int a = 5; int b= 10;

Good typesetting:

int a = 5;int b = 10;

18.2 comma, semicolon only after adding a space, binocular operator before and after the space,-> with.
18.3 the comment and comment content are separated by a space.

3. The format of the code that I used to write C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.