C++ Coding Standards

References

Naming

General Naming Rules

int num_errors;                  // Good.

int num_completed_connections;   // Good.

 

int n;                           // Bad - meaningless.

int nerr;                        // Bad - ambiguous abbreviation.

int n_comp_conns;                // Bad - ambiguous abbreviation.

// Good

// These show proper names with no abbreviations.

int num_dns_connections;         // Most people know what "DNS" stands for.

int price_count_reader;          // OK, price count. Makes sense.

 

// Bad!

// Abbreviations can be confusing or ambiguous outside a small group.

int wgc_connections;             // Only your group knows what this stands for.

int pc_reader;                   // Lots of things can be abbreviated "pc".

File Names

my_useful_class.cpp

my-useful-class.cpp

myusefulclass.cpp

myusefulclass_test.cpp           // _unittest and _regtest are deprecated.

 

url_table.h                      // The class declaration.

url_table.cpp                    // The class definition.

url_table-inl.h                  // Inline functions that include lots of code.

Type Names

// classes and structs

class UrlTable { ...

class UrlTableTester { ...

struct UrlTableProperties { ...

 

// typedefs

typedef hash_map<UrlTableProperties *, string> PropertiesMap;

 

// enums

enum UrlTableErrors { ...

Variable Names

// Common Variable names

string table_name;              // OK - uses underscore.

string tablename;               // OK - all lowercase.

string tableName;               // Bad - mixed case.

 

// Class Data Members

string _table_name;             // OK - underscore at first.

string _tablename;              // OK.

Constant Names

const int DAYSINWEEK = 7;       // OK - all uppercase.

Function Names

// Regular Functions

AddTableEntry()

DeleteUrl()

OpenFileOrDie()

 

// Accessors and Mutators

class MyClass

{

public:

    MyClass()

    {

    }

 

    ~MyClass()

    {

    }

 

    int get_num_entries() const

    {

        return _num_entries;

    }

 

    void set_num_entries(int num_entries)

    {

        _num_entries = num_entries;

    }

private:

    int _num_entries;

};

Macro Names

#define ROUND(x) ...

#define PI_ROUNDED 3.0

Formatting

  • Line Length
    • Each line of text in your code should be at most 80 characters long.
  • Non-ASCII Characters
  • Spaces vs. Tabs
    • Indent 4 spaces at a time.
  • Function Declarations and Definitions
    • Return type on the same line as function name, parameters on the same line if they fit.

// Functions look like this:

ReturnType ClassName::FunctionName(Type par_name1, Type par_name2)

{

    DoSomething();

    ...

}

 

// If you have too much text to fit on one line:

ReturnType ClassName::ReallyLongFunctionName(Type par_name1, Type par_name2,

                                             Type par_name3)

{

    DoSomething();

    ...

}

 

// or if you cannot fit even the first parameter:

ReturnType LongClassName::ReallyReallyReallyLongFunctionName(

    Type par_name1,  // 4 space indent

    Type par_name2,

    Type par_name3)

{

    DoSomething();   // 4 space indent

    ...

}

 

// Everything in this function signature fits on a single line

ReturnType 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

{

    ...

}

 

// 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) {}

  • Function Calls
    • On one line if it fits; otherwise, wrap arguments at the parenthesis.

//Function calls have the following format:

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

 

// If the arguments do not all fit on one line, they should be broken up onto multiple lines,

// with each subsequent line aligned with the first argument.

// Do not add spaces after the open paren or before the close paren:

bool retval = DoSomething(averyveryveryverylongargument1,

                          argument2, argument3);

 

// If the function has many arguments, consider having one per line

bool retval = DoSomething(argument1,

                          argument2,

                          argument3,

                          argument4);

 

// If the function signature is so long that it cannot fit within the maximum line length

if (...)

{

    ...

    ...

    if (...)

    {

        DoSomethingThatRequiresALongFunctionName(

            very_long_argument1,  // 4 space indent

            argument2,

            argument3,

            argument4);

    }

 

}

  • Conditionals

if (condition) // no spaces inside parentheses

{

    ...        // 4 space indent.

}

else if (...)  // The else goes on the new line

{

    ...

}

else

{

    ...

}

 

if(condition)     // Bad - space missing after IF.

if(condition){    // Doubly bad.

 

// Short conditional statements still need the parentheses

if (x == kFoo)

{

    return new Foo();

}

 

// Not allowed - if statement on one line when there is an else clause

if (x) DoThis();

else DoThat();

  • Loops and Switch Statements

switch (var)

{

    case 0:

    {

        ...      // 4 space indent

        break;

    }

    case 1:

    {

        ...

        break;

    }

    default:

    {

        assert(false);

    }

}

 

// Empty loop bodies should use {}, but not a single semicolon.

while (condition)

{

    // Repeat test until it returns false.

}

 

for (int i = 0; i < kSomeNumber; ++i)

{

}  // Good - empty body.

 

while (condition);  // Bad - looks like part of do/while loop.

  • Pointer and Reference Expressions

// No spaces around period or arrow. Pointer operators do not have trailing spaces.

x = *p;

p = &x;

x = r.y;

x = r->y;

 

// 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 &

  • Boolean Expressions

if (this_one_thing > this_other_thing &&

    a_third_thing == a_fourth_thing &&

    yet_another && last_one)

{

    ...

}

Header Files

Classes

相关工具

CppCheck

AStyle

Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.

Memory Track

 

posted @ 2013-04-25 10:59  重庆Debug  阅读(290)  评论(0编辑  收藏  举报