SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
C and C++ Coding Style




      blackball
Contents

  -Naming
     -Comments
        -Formatting
            -Head files
               -Scoping
                   -Classes
                          -Other C++ features
                                -Exception to the rules
                                       -Cpplint
This page intentionally left blank for relax
Naming

  -The most important consistency rules are those that govern naming.
  -Rules
     -Function names, variable names, and filenames should be descriptive;
     -Eschew abbreviation.
     -Types and variables should be nouns,while functions should be "command" verbs.

  -Bad examples
     -void count( int[]           arr, int value ); // count what ?
     -int error_cnt; // error_count ?
     -int j,k,l; // always make programs smell bad


  -ref. naming.cc
Comments

 -Comments are absolutely vital to keeping our code readable
 -Rules
    -Be consistent with //... or /*... */

    -File copyright notice, description and author information etc.
    -Comment to describe why, how, and what.
    -TODO comments

 -Bad examples
    -mixed // and /* */
    -// this is the first function I made.



 -ref. comments.cc
Formatting

  -A project is much easier to follow if everyone uses the same style.
  -Rules
     -Each line of text in your code should be at most 80 characters long.
     -Non-ASCII characters should be rare, and must use UTF-8 formatting.
     -Use only spaces, and indent 2 spaces at a time.
     -Return type on the same line as function name, parameters on the same line if they fit.
     -Prefer no spaces inside parentheses. The else keyword belongs on a new line.
     -Switch statements may use braces for blocks. Empty loop bodies should use {} or continue.
     -No spaces around period or arrow. Pointer operators do not have trailing spaces.
     -Variable or array initialization use = or ( ).
     -a preprocessor directive should always be at the beginning of the line.
     -Sections in public, protected and private order, each indented one space.
     -The contents of namespaces are not indented.


  -ref. formatting.cc
Head files

  -Make a huge difference to the readability, size and performance of code.
  -Rules
     -one source file for one header file, in general.
     -#define guards to prevent multiple inclusion.
     -The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H .
     -Don't use an #include when a forward declaration would suffice.
     -Define functions inline only when they are small, say, 10 lines or less.
     -You may use file names with a -inl.h suffix to define complex inline functions when needed.
     -When defining a function, parameter order is: inputs, then outputs.
     -Include order: your .h → 3rd lib .h → C lib .h → C++ lib .



  -ref. head_files.cc
Scoping

  -Avoid runtime naming conflicts, save compiling time, etc.
  -Rules
     -Unnamed namespaces in .cc files are encouraged, Do not use a using-directive.
     -Do not declare anything in namespace std even forward declarations of standard library classes.
     -Put nested class in a namespace to keep declarations out of the global scope.
     -Prefer nonmember or static member functions within a namespace; use global function rarely.
     -Place function's variables in the narrowest scope possible, and initialize them in the declaration.
     -Static or global variables of class type are forbidden.



  -ref. scoping.cc
Classes

  -Classes are the fundamental unit of code in C++.
  -Rules
      -constructors set member variables to initial values.   Init() method for complex initialization.
      -Define a default constructor if you defines member variables and has no other constructors.
      -Use the C++ keyword explicit for constructors with one argument.
      -Provide a copy constructor and assignment operator only when necessary.
      -Use a struct only for passive objects that carry data; everything else is a class.
      -Appropriate Composition than inheritance. When using inheritance, make it public.
      -Multiple implementation inheritance is a bad idea in most issues.
      -Classes satisfy certain conditions are allowed, but not required, to end with an Interface suffix.
      -Do not overload operators except in rare, special circumstances.
      -Make data members private, and provide access method to them.
      - public: before private:, methods before data members (variables), etc.
      -Prefer small and focused functions.



  - ref. classes.cc
Other C++ features
  -Details make things boring, details make things shining.
  -Rules
     -All parameters passed by reference must be labeled const.
     -Function overload permitted when same usage different parameters.
     -Not allow default function parameters.
     -Not allow variable-length arrays or alloca().
     -Use of friend classes and functions, within reason.
     -Not use C++ exceptions // if you want, think twice.
     -Not use Run Time Type Information(RTTI).
     -Use C++ casts like static_cast<>(). Do not use cast formats like int y = (int)x; or int y = int(x);
     -Use streams only for logging.
     -Use prefix form (++i) of the increment and decrement operators.
     -strongly recommend to use const.
     -Prefer to use int16_t, uint32_t, int64_t in stdint.h
     -Be very cautious with macros. Prefer inline functions, enums, and const variables to macros
     -Use 0 for integers, 0.0 for reals, NULL for pointers, and '0' for chars.
     -se sizeof(varname) instead of sizeof(type) whenever possible.
Exceptions to the rules

  -Exceptions always should be in control.
  -Rules
      -Use C++ types not DWORD, HANDLE,etc in your code except you are making Windows API.
      -Treat all warnings as errors when you under MS VC++.
      -Do not use #pragma once.
      -Always have reasons when you think you're facing an exception.



  -ref. previous rules.
Cpplint

  -A tool for checking coding style(Google), in Python.
  -Set up Python environment and type:
     python cpplint.py your_source_file.cc

  -More options, just type:
     python cpplint.py

  -or read the documentation in the source code.


  -ref. cpplint_check.cc
Conclusion




         Use common sense and BE CONSISTENT.
Thank You

   Q&A

Weitere ähnliche Inhalte

Was ist angesagt? (7)

Jerry Shea Resume And Addendum 5 2 09
Jerry  Shea Resume And Addendum 5 2 09Jerry  Shea Resume And Addendum 5 2 09
Jerry Shea Resume And Addendum 5 2 09
 
Paulo Freire Pedagpogia 1
Paulo Freire Pedagpogia 1Paulo Freire Pedagpogia 1
Paulo Freire Pedagpogia 1
 
Washington Practitioners Significant Changes To Rpc 1.5
Washington Practitioners Significant Changes To Rpc 1.5Washington Practitioners Significant Changes To Rpc 1.5
Washington Practitioners Significant Changes To Rpc 1.5
 
PHPDoc
PHPDocPHPDoc
PHPDoc
 
Unit 1-introduction to perl
Unit 1-introduction to perlUnit 1-introduction to perl
Unit 1-introduction to perl
 
PHP Standards Recommendations - PHP-FIG
PHP Standards Recommendations - PHP-FIGPHP Standards Recommendations - PHP-FIG
PHP Standards Recommendations - PHP-FIG
 
Presentation on C++ programming
Presentation on C++ programming Presentation on C++ programming
Presentation on C++ programming
 

Andere mochten auch

2010 bodley and blackwells
2010 bodley and blackwells2010 bodley and blackwells
2010 bodley and blackwells
Richard Ovenden
 
2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee
guestc8e3279
 
James Caan Business Secrets App
James Caan Business Secrets AppJames Caan Business Secrets App
James Caan Business Secrets App
JamesCaan
 
Unsupervised Feature Learning
Unsupervised Feature LearningUnsupervised Feature Learning
Unsupervised Feature Learning
Amgad Muhammad
 

Andere mochten auch (20)

Week10
Week10Week10
Week10
 
JS patterns
JS patternsJS patterns
JS patterns
 
2010 bodley and blackwells
2010 bodley and blackwells2010 bodley and blackwells
2010 bodley and blackwells
 
RAII and ScopeGuard
RAII and ScopeGuardRAII and ScopeGuard
RAII and ScopeGuard
 
Presentation for Advanced Detection and Remote Sensing: Radar Systems
Presentation for Advanced Detection and Remote Sensing:  Radar SystemsPresentation for Advanced Detection and Remote Sensing:  Radar Systems
Presentation for Advanced Detection and Remote Sensing: Radar Systems
 
Infographic: The Dutch Games Market
Infographic: The Dutch Games MarketInfographic: The Dutch Games Market
Infographic: The Dutch Games Market
 
MedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS Animal Experiments
MedicReS Animal Experiments
 
2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee
 
FactorEx - электронный факторинг
FactorEx - электронный факторинг FactorEx - электронный факторинг
FactorEx - электронный факторинг
 
James Caan Business Secrets App
James Caan Business Secrets AppJames Caan Business Secrets App
James Caan Business Secrets App
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 
Estilos y paradigmas de la Interacción Humano-Computador
Estilos y paradigmas de la Interacción Humano-ComputadorEstilos y paradigmas de la Interacción Humano-Computador
Estilos y paradigmas de la Interacción Humano-Computador
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
How to manage Hortonworks HDB Resources with YARN
How to manage Hortonworks HDB Resources with YARNHow to manage Hortonworks HDB Resources with YARN
How to manage Hortonworks HDB Resources with YARN
 
Unsupervised Feature Learning
Unsupervised Feature LearningUnsupervised Feature Learning
Unsupervised Feature Learning
 
EMRでスポットインスタンスの自動入札ツールを作成する
EMRでスポットインスタンスの自動入札ツールを作成するEMRでスポットインスタンスの自動入札ツールを作成する
EMRでスポットインスタンスの自動入札ツールを作成する
 
Как обосновать затраты на ИБ?
Как обосновать затраты на ИБ?Как обосновать затраты на ИБ?
Как обосновать затраты на ИБ?
 
Microservice Architecture on AWS using AWS Lambda and Docker Containers
Microservice Architecture on AWS using AWS Lambda and Docker ContainersMicroservice Architecture on AWS using AWS Lambda and Docker Containers
Microservice Architecture on AWS using AWS Lambda and Docker Containers
 
Customer Success Strategy Template
Customer Success Strategy TemplateCustomer Success Strategy Template
Customer Success Strategy Template
 

Ähnlich wie Presentation

c-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.pptc-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.ppt
VinayakHospet1
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
faithxdunce63732
 
CodingStandardsDoc
CodingStandardsDocCodingStandardsDoc
CodingStandardsDoc
Amol Patole
 

Ähnlich wie Presentation (20)

New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
 
c-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.pptc-coding-standards-and-best-programming-practices.ppt
c-coding-standards-and-best-programming-practices.ppt
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
(4) cpp abstractions references_copies_and_const-ness
(4) cpp abstractions references_copies_and_const-ness(4) cpp abstractions references_copies_and_const-ness
(4) cpp abstractions references_copies_and_const-ness
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
7986-lect 7.pdf
7986-lect 7.pdf7986-lect 7.pdf
7986-lect 7.pdf
 
Basics of C
Basics of CBasics of C
Basics of C
 
Programming style guideline very good
Programming style guideline very goodProgramming style guideline very good
Programming style guideline very good
 
Google Objective-C Style Guide
Google Objective-C Style GuideGoogle Objective-C Style Guide
Google Objective-C Style Guide
 
Google Objective-C Style Guide
Google Objective-C Style GuideGoogle Objective-C Style Guide
Google Objective-C Style Guide
 
Ruby on Rails: Coding Guideline
Ruby on Rails: Coding GuidelineRuby on Rails: Coding Guideline
Ruby on Rails: Coding Guideline
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Linters in R
Linters in RLinters in R
Linters in R
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
Android coding standard
Android coding standard Android coding standard
Android coding standard
 
CodingStandardsDoc
CodingStandardsDocCodingStandardsDoc
CodingStandardsDoc
 
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
 
Chtp415
Chtp415Chtp415
Chtp415
 

Presentation

  • 1. C and C++ Coding Style blackball
  • 2. Contents -Naming -Comments -Formatting -Head files -Scoping -Classes -Other C++ features -Exception to the rules -Cpplint
  • 3. This page intentionally left blank for relax
  • 4. Naming -The most important consistency rules are those that govern naming. -Rules -Function names, variable names, and filenames should be descriptive; -Eschew abbreviation. -Types and variables should be nouns,while functions should be "command" verbs. -Bad examples -void count( int[] arr, int value ); // count what ? -int error_cnt; // error_count ? -int j,k,l; // always make programs smell bad -ref. naming.cc
  • 5. Comments -Comments are absolutely vital to keeping our code readable -Rules -Be consistent with //... or /*... */ -File copyright notice, description and author information etc. -Comment to describe why, how, and what. -TODO comments -Bad examples -mixed // and /* */ -// this is the first function I made. -ref. comments.cc
  • 6. Formatting -A project is much easier to follow if everyone uses the same style. -Rules -Each line of text in your code should be at most 80 characters long. -Non-ASCII characters should be rare, and must use UTF-8 formatting. -Use only spaces, and indent 2 spaces at a time. -Return type on the same line as function name, parameters on the same line if they fit. -Prefer no spaces inside parentheses. The else keyword belongs on a new line. -Switch statements may use braces for blocks. Empty loop bodies should use {} or continue. -No spaces around period or arrow. Pointer operators do not have trailing spaces. -Variable or array initialization use = or ( ). -a preprocessor directive should always be at the beginning of the line. -Sections in public, protected and private order, each indented one space. -The contents of namespaces are not indented. -ref. formatting.cc
  • 7. Head files -Make a huge difference to the readability, size and performance of code. -Rules -one source file for one header file, in general. -#define guards to prevent multiple inclusion. -The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H . -Don't use an #include when a forward declaration would suffice. -Define functions inline only when they are small, say, 10 lines or less. -You may use file names with a -inl.h suffix to define complex inline functions when needed. -When defining a function, parameter order is: inputs, then outputs. -Include order: your .h → 3rd lib .h → C lib .h → C++ lib . -ref. head_files.cc
  • 8. Scoping -Avoid runtime naming conflicts, save compiling time, etc. -Rules -Unnamed namespaces in .cc files are encouraged, Do not use a using-directive. -Do not declare anything in namespace std even forward declarations of standard library classes. -Put nested class in a namespace to keep declarations out of the global scope. -Prefer nonmember or static member functions within a namespace; use global function rarely. -Place function's variables in the narrowest scope possible, and initialize them in the declaration. -Static or global variables of class type are forbidden. -ref. scoping.cc
  • 9. Classes -Classes are the fundamental unit of code in C++. -Rules -constructors set member variables to initial values. Init() method for complex initialization. -Define a default constructor if you defines member variables and has no other constructors. -Use the C++ keyword explicit for constructors with one argument. -Provide a copy constructor and assignment operator only when necessary. -Use a struct only for passive objects that carry data; everything else is a class. -Appropriate Composition than inheritance. When using inheritance, make it public. -Multiple implementation inheritance is a bad idea in most issues. -Classes satisfy certain conditions are allowed, but not required, to end with an Interface suffix. -Do not overload operators except in rare, special circumstances. -Make data members private, and provide access method to them. - public: before private:, methods before data members (variables), etc. -Prefer small and focused functions. - ref. classes.cc
  • 10. Other C++ features -Details make things boring, details make things shining. -Rules -All parameters passed by reference must be labeled const. -Function overload permitted when same usage different parameters. -Not allow default function parameters. -Not allow variable-length arrays or alloca(). -Use of friend classes and functions, within reason. -Not use C++ exceptions // if you want, think twice. -Not use Run Time Type Information(RTTI). -Use C++ casts like static_cast<>(). Do not use cast formats like int y = (int)x; or int y = int(x); -Use streams only for logging. -Use prefix form (++i) of the increment and decrement operators. -strongly recommend to use const. -Prefer to use int16_t, uint32_t, int64_t in stdint.h -Be very cautious with macros. Prefer inline functions, enums, and const variables to macros -Use 0 for integers, 0.0 for reals, NULL for pointers, and '0' for chars. -se sizeof(varname) instead of sizeof(type) whenever possible.
  • 11. Exceptions to the rules -Exceptions always should be in control. -Rules -Use C++ types not DWORD, HANDLE,etc in your code except you are making Windows API. -Treat all warnings as errors when you under MS VC++. -Do not use #pragma once. -Always have reasons when you think you're facing an exception. -ref. previous rules.
  • 12. Cpplint -A tool for checking coding style(Google), in Python. -Set up Python environment and type: python cpplint.py your_source_file.cc -More options, just type: python cpplint.py -or read the documentation in the source code. -ref. cpplint_check.cc
  • 13. Conclusion Use common sense and BE CONSISTENT.
  • 14. Thank You Q&A