SlideShare ist ein Scribd-Unternehmen logo
1 von 8
A C++ Programming Style Guideline
Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the
readability of programs is also important. There are many "standards" in use. Since following them will
not guarantee good code, these "standards" actually are guidelines of style. Each one has its proponents
and detractors. The textbook advocates one particular style for C++ programs. This document collects the
style comments in the textbook into one place and adds some documentation requirements for this course.
The essential point is that a program is a medium of communication between humans; a clear, consistent
style will make it that much easier for you to communicate.
The following programming style guideline must be followed in all assignments of the course.
Program Documentation
Main Program Heading
The main program file should begin with a comment section of the following form and with the following
information filled in:
// File: <name of file>
// < Description of what the program does >
//
// Input: < Description of data that the program asks the user for
// or reads from a file >
// Output: < Description of what the program outputs as a result
// either to the screen or to a file >
// ------------------------------------------------------------------
// Class: Instructor:
// Assignment: Date assigned:
// Programmer: Date completed:
Preprocessor Section
In the preprocessor section, include statements for header files should have comments indicating the
types, constants, variables, or functions used from the header. For example,
#include <iostream> // cin, cout, <<, >>, endl
#include <cmath> // sin, cos
#include "list.h" // List class
Analysis and Design of Main Program
If assigned, the analysis and design of the main program should precede the main program function. For
example:
// Analysis of main program
// Objects Type Kind Name
// ---------------------------------------------------------
// Fahrenheit temperature double variable fahrenheit
// Celsius temperature double variable celsius
//
// Design of main program
// 1. Read in fahrenheit
// 2. Compute celsius = 5/9 (fahrenheit – 32)
// 3. Display fahrenheit
int main ()
Function Headings
If assigned, the analysis and design of a function should precede the function definition. No other heading
documentation is required in this case. For example:
// Analysis of ComputeCircleArea
// Objects Type Kind Movement Name
// ---------------------------------------------------------
// Radius of circle double variable received radius
// Area of circle double variable returned -----
//
// Design of ComputeCircleArea
// 1. Return radius * radius * PI
double ComputeCircleArea (double radius)
If an analysis and design for a function is not required, include heading documentation, as needed, of the
following form for each such function:
// Function: <name of function>
// Returns: <returned object, if any>
//
// < Short description of what function does >
// < Assumptions about the values of the received parameters >
void Sample (type1 arg1, // REC’D: <short description of object>
type2& arg2,...) // PBACK: <short description of object>
{
...
} // end Sample
There should be one formal parameter per line, lined up under each other as shown above with comments
about the movement and description of the parameter. The movement of a parameter is in relation to the
function and refers to whether the data is received from the caller or passed back to the caller.
Identifiers
Identifiers should be chosen to be self-documenting. Abbreviations, except where standard, should be
avoided. In addition, comment variables when usage is restricted. (E.g., an integer used to represent a
calendar month, so its valid values are 1-12.)
Each word in a function identifier, class identifier, or structure type identifier should start with an
uppercase letter. E.g., FindMinIndex or Point. Each word except the first one in an variable identifier
should start with an uppercase letter. E.g., firstName. Constant identifiers should be written in all
uppercase with words separated by an underscore (_). E.g., MAX_STRING_SIZE.
Commenting
Comment the ending curly brace of each compound statement. Such comments should start with //end
along with a brief, mnemonic, and unique (within the function or main program) comment. For example,
// Function: Try
// Attempts to do some things...
void Try (...)
{
...
while (!done)
{
...
} // end while there are things left to do
...
} // end Try
Comment the ends of struct, class, and function definitions with the name of the type or function
being defined as shown above.
Comment code to improve clarity. Comments should tell WHAT is being done or WHY it is being done,
not how it is being done. Often these comments will be phrases that would be found in the analysis and
design. For example,
// Adjust i to point to the end of the previous word:
i = i - 1;
is better than
// Subtract 1 from i:
i = i - 1;
Comments should be in good English. Grammar and spelling should be correct. Abbreviations in
comments should rarely be used, and then only those that would be found in a standard dictionary.
Constants and Variables
Constants
Constants in your algorithm should be replaced by constant identifiers in your program. Exceptions
should be made only when the constant conveys its own meaning, such as 0 as an initial value for a sum
or to start a count, or is part of a constant mathematical formula, such as 2 in 2r. Generally constants
should be declared globally.
Variable use
Each variable identifier that occurs in a function should be local to that function - that is, declared in the
function's header or in the function's body.
1. If the variable may have its value changed in the body of the function and that new value will be
needed back in the calling program (i.e., it is passed back), then the variable should be declared as
a reference formal parameter. (Sometimes data is both received and passed back.)
2. If the variable gets its initial value from the calling program but does not send a different value
back (i.e., it is only received), then the variable should be declared as a value formal parameter,
except for C++ arrays, which are automatically passed as reference parameters. Also when
efficiency of copying is a concern, large structures like structs or class objects should be declared
as constant reference formal parameters. For example,
int Function1 (const vector<int> & v) // REC’D:...
3. If the variable does not get its initial value from the calling program and does not pass its value
back (via a parameter), then the variable should be declared as a local variable of the function.
This generally includes the returned object, if any.
NEVER use a global variable in this course unless explicitly told otherwise. While there are valid reasons
for having global variables, they generally should be avoided and will not be tolerated in this course.
Program Formatting
Any preprocessor statements (include, define, etc.) should be at the beginning of a file (after the
program file heading comment). Any global constants should follow. Finally, function prototypes should
appear just before the main function. No other statements should appear outside a function body unless
explicitly allowed.
All local constants should be declared at the beginning of a function or main program before any
executable statements. Local variables should be declared just before first use. If at all possible, variables
should be initialized when declared.
A blank line should be used to separate logical sections of a program or function. In general, blank lines
should be used wherever their use will improve readability.
Indenting should be used to convey structure. Indentation should be at least 3 spaces, and generally no
more that 6 spaces unless otherwise noted. Indenting should be consistent.
For declarations, each identifier should be declared on a separate line. Variable declarations should be
indented, and the variables of that type should line up under each other. Use commas to separate variable
identifiers of the same type. Comments should explain the purpose of each constant or variable where
appropriate, and should line up under each other. For example, in the main function, we might declare:
const int MAX_SIZE = 100; // Maximum size of array
const double G = 9.8; // Gravitational constant m/s/s
int main (int argc, char *argv[])
{
int i, // Outer loop index
j, // Inner loop index
tests[MAX_SIZE]; // Array of test scores
Point p1;
...
} // end main
A statement should not be longer than a screen's width (about 80 characters). If a non-I/O, non-function
call statement must be continued on more than one line, the second line should be indented to at least 6
spaces and successive continuation lines should be aligned with the second line of the statement. For
example, we might write
while ((('a' <= line [i]) && (line[i] <= 'z'))
|| (('A' <= line[i]) && (line[i] <= 'Z')))
i++;
An I/O statement should be broken up so that the << or >> operators line up. For example, we might
write
cout << setw(15) << name << setw(30) << address
<< setw(15) << phone << endl;
A long function call statement should be broken up so that the function arguments lined up. For example,
we might write
Sample (argument1, argument2, argument3,
argument4, argument5, argument6);
Whenever there is if, else, while, for, do, and switch, the curly braces should be used. They should
line up under the first line for that statement. Each line of the body of a compound statement should be
indented. should start on the next line and be indented. For example,
if (first <= last)
{
found = true;
}
if (a [middle] = item)
{
item = a [middle];
found = true;
position = middle;
} // end if match found
Column alignment should be observed for each set of reserved words if and else. This include multi-
branch constructs, for example:
if (x > 90)
{
grade = 'A';
}
else if (x > 80)
{
grade = 'B';
}
else if (x > 70)
{
grade = 'C';
}
else if (x > 60)
{
grade = 'C';
}
else
{
grade = 'D';
}
Comments that describe one or more statements should be immediately above and aligned with the
statement or collection of statements which they describe. There should be a blank line before such
comments. For example,
j = i;
while ((j > 1) && (a [j - 1] > a [j]))
{
// a [1..j-1] is unsorted and a [j..i] sorted:
Swap (a [j], a [j - 1]);
j = j - 1
} // end while
The main curly braces for functions should line up with the corresponding heading. For example,
void FindMinIndex (...)
{
...
} // end FindMinIndex
At least one space should be used in the following locations within C++ text (this does not apply within
comments and character strings):
‱ before and after =, //, any relational, logical, arithmetic, or assignment operator
‱ before (
‱ after a comma in argument lists, and after semicolon in for loop headings
A function should fit on one screen (about 25 lines) if possible and must fit on a listing page (about 50
lines). Ideally, the analysis and design will not produce code that is more than a page long, but if the code
does not fit initially, introduce one or more new functions to split up the work in logical places.

Weitere Àhnliche Inhalte

Was ist angesagt?

Program slicing
Program slicing Program slicing
Program slicing Feras Tanan
 
DBMS 2011
DBMS 2011DBMS 2011
DBMS 2011Atiqa khan
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILEDipta Saha
 
C fundamental
C fundamentalC fundamental
C fundamentalSelvam Edwin
 
Chapter 13.1.6
Chapter 13.1.6Chapter 13.1.6
Chapter 13.1.6patcha535
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSivakumar R D .
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmigAppili Vamsi Krishna
 
Savitch ch 04
Savitch ch 04Savitch ch 04
Savitch ch 04Terry Yoast
 
Lecture11 abap on line
Lecture11 abap on lineLecture11 abap on line
Lecture11 abap on lineMilind Patil
 
SAP Modularization techniques
SAP Modularization techniquesSAP Modularization techniques
SAP Modularization techniquesJugul Crasta
 
Basic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartBasic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartPrasanna R Kovath
 
Passing table to subroutine
Passing table to subroutinePassing table to subroutine
Passing table to subroutineRajee Chandru
 
Complete list of all sap abap keywords
Complete list of all sap abap keywordsComplete list of all sap abap keywords
Complete list of all sap abap keywordsPrakash Thirumoorthy
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQLPooja Dixit
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul
 

Was ist angesagt? (20)

Ch13
Ch13Ch13
Ch13
 
C functions list
C functions listC functions list
C functions list
 
SAS Macro
SAS MacroSAS Macro
SAS Macro
 
Program slicing
Program slicing Program slicing
Program slicing
 
DBMS 2011
DBMS 2011DBMS 2011
DBMS 2011
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Chapter 13.1.6
Chapter 13.1.6Chapter 13.1.6
Chapter 13.1.6
 
Sample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.SivakumarSample for Simple C Program - R.D.Sivakumar
Sample for Simple C Program - R.D.Sivakumar
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Savitch ch 04
Savitch ch 04Savitch ch 04
Savitch ch 04
 
C language ppt
C language pptC language ppt
C language ppt
 
Lecture11 abap on line
Lecture11 abap on lineLecture11 abap on line
Lecture11 abap on line
 
SAP Modularization techniques
SAP Modularization techniquesSAP Modularization techniques
SAP Modularization techniques
 
Basic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chartBasic syntax : Algorithm,Flow chart
Basic syntax : Algorithm,Flow chart
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Passing table to subroutine
Passing table to subroutinePassing table to subroutine
Passing table to subroutine
 
Complete list of all sap abap keywords
Complete list of all sap abap keywordsComplete list of all sap abap keywords
Complete list of all sap abap keywords
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Open Gurukul Language PL/SQL
Open Gurukul Language PL/SQLOpen Gurukul Language PL/SQL
Open Gurukul Language PL/SQL
 

Ähnlich wie C++ Programming Style Guide

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.docxfaithxdunce63732
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAMAN ANAND
 
Library management system
Library management systemLibrary management system
Library management systemSHARDA SHARAN
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdfHome
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programmingnmahi96
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptxChapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptxrajinevitable05
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro headerhasan Mohammad
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1Vikram Nandini
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of ckinish kumar
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxPragatheshP
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diarySHARDA SHARAN
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
 

Ähnlich wie C++ Programming Style Guide (20)

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
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Library management system
Library management systemLibrary management system
Library management system
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Functions-Computer programming
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
C question
C questionC question
C question
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptxChapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
6 preprocessor macro header
6 preprocessor macro header6 preprocessor macro header
6 preprocessor macro header
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Basic construction of c
Basic construction of cBasic construction of c
Basic construction of c
 
Unit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptxUnit 2 CMath behind coding.pptx
Unit 2 CMath behind coding.pptx
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diary
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
lecture1 pf.pptx
lecture1 pf.pptxlecture1 pf.pptx
lecture1 pf.pptx
 

KĂŒrzlich hochgeladen

EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxElton John Embodo
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...SeĂĄn Kennedy
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)lakshayb543
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 

KĂŒrzlich hochgeladen (20)

EMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docxEMBODO Lesson Plan Grade 9 Law of Sines.docx
EMBODO Lesson Plan Grade 9 Law of Sines.docx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
Visit to a blind student's school🧑‍🩯🧑‍🩯(community medicine)
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 

C++ Programming Style Guide

  • 1. A C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also important. There are many "standards" in use. Since following them will not guarantee good code, these "standards" actually are guidelines of style. Each one has its proponents and detractors. The textbook advocates one particular style for C++ programs. This document collects the style comments in the textbook into one place and adds some documentation requirements for this course. The essential point is that a program is a medium of communication between humans; a clear, consistent style will make it that much easier for you to communicate. The following programming style guideline must be followed in all assignments of the course. Program Documentation Main Program Heading The main program file should begin with a comment section of the following form and with the following information filled in: // File: <name of file> // < Description of what the program does > // // Input: < Description of data that the program asks the user for // or reads from a file > // Output: < Description of what the program outputs as a result // either to the screen or to a file > // ------------------------------------------------------------------ // Class: Instructor: // Assignment: Date assigned: // Programmer: Date completed: Preprocessor Section In the preprocessor section, include statements for header files should have comments indicating the types, constants, variables, or functions used from the header. For example, #include <iostream> // cin, cout, <<, >>, endl #include <cmath> // sin, cos #include "list.h" // List class
  • 2. Analysis and Design of Main Program If assigned, the analysis and design of the main program should precede the main program function. For example: // Analysis of main program // Objects Type Kind Name // --------------------------------------------------------- // Fahrenheit temperature double variable fahrenheit // Celsius temperature double variable celsius // // Design of main program // 1. Read in fahrenheit // 2. Compute celsius = 5/9 (fahrenheit – 32) // 3. Display fahrenheit int main () Function Headings If assigned, the analysis and design of a function should precede the function definition. No other heading documentation is required in this case. For example: // Analysis of ComputeCircleArea // Objects Type Kind Movement Name // --------------------------------------------------------- // Radius of circle double variable received radius // Area of circle double variable returned ----- // // Design of ComputeCircleArea // 1. Return radius * radius * PI double ComputeCircleArea (double radius) If an analysis and design for a function is not required, include heading documentation, as needed, of the following form for each such function: // Function: <name of function> // Returns: <returned object, if any> // // < Short description of what function does > // < Assumptions about the values of the received parameters > void Sample (type1 arg1, // REC’D: <short description of object> type2& arg2,...) // PBACK: <short description of object> {
  • 3. ... } // end Sample There should be one formal parameter per line, lined up under each other as shown above with comments about the movement and description of the parameter. The movement of a parameter is in relation to the function and refers to whether the data is received from the caller or passed back to the caller. Identifiers Identifiers should be chosen to be self-documenting. Abbreviations, except where standard, should be avoided. In addition, comment variables when usage is restricted. (E.g., an integer used to represent a calendar month, so its valid values are 1-12.) Each word in a function identifier, class identifier, or structure type identifier should start with an uppercase letter. E.g., FindMinIndex or Point. Each word except the first one in an variable identifier should start with an uppercase letter. E.g., firstName. Constant identifiers should be written in all uppercase with words separated by an underscore (_). E.g., MAX_STRING_SIZE. Commenting Comment the ending curly brace of each compound statement. Such comments should start with //end along with a brief, mnemonic, and unique (within the function or main program) comment. For example, // Function: Try // Attempts to do some things... void Try (...) { ... while (!done) { ... } // end while there are things left to do ... } // end Try Comment the ends of struct, class, and function definitions with the name of the type or function being defined as shown above.
  • 4. Comment code to improve clarity. Comments should tell WHAT is being done or WHY it is being done, not how it is being done. Often these comments will be phrases that would be found in the analysis and design. For example, // Adjust i to point to the end of the previous word: i = i - 1; is better than // Subtract 1 from i: i = i - 1; Comments should be in good English. Grammar and spelling should be correct. Abbreviations in comments should rarely be used, and then only those that would be found in a standard dictionary. Constants and Variables Constants Constants in your algorithm should be replaced by constant identifiers in your program. Exceptions should be made only when the constant conveys its own meaning, such as 0 as an initial value for a sum or to start a count, or is part of a constant mathematical formula, such as 2 in 2r. Generally constants should be declared globally. Variable use Each variable identifier that occurs in a function should be local to that function - that is, declared in the function's header or in the function's body. 1. If the variable may have its value changed in the body of the function and that new value will be needed back in the calling program (i.e., it is passed back), then the variable should be declared as a reference formal parameter. (Sometimes data is both received and passed back.) 2. If the variable gets its initial value from the calling program but does not send a different value back (i.e., it is only received), then the variable should be declared as a value formal parameter, except for C++ arrays, which are automatically passed as reference parameters. Also when
  • 5. efficiency of copying is a concern, large structures like structs or class objects should be declared as constant reference formal parameters. For example, int Function1 (const vector<int> & v) // REC’D:... 3. If the variable does not get its initial value from the calling program and does not pass its value back (via a parameter), then the variable should be declared as a local variable of the function. This generally includes the returned object, if any. NEVER use a global variable in this course unless explicitly told otherwise. While there are valid reasons for having global variables, they generally should be avoided and will not be tolerated in this course. Program Formatting Any preprocessor statements (include, define, etc.) should be at the beginning of a file (after the program file heading comment). Any global constants should follow. Finally, function prototypes should appear just before the main function. No other statements should appear outside a function body unless explicitly allowed. All local constants should be declared at the beginning of a function or main program before any executable statements. Local variables should be declared just before first use. If at all possible, variables should be initialized when declared. A blank line should be used to separate logical sections of a program or function. In general, blank lines should be used wherever their use will improve readability. Indenting should be used to convey structure. Indentation should be at least 3 spaces, and generally no more that 6 spaces unless otherwise noted. Indenting should be consistent. For declarations, each identifier should be declared on a separate line. Variable declarations should be indented, and the variables of that type should line up under each other. Use commas to separate variable identifiers of the same type. Comments should explain the purpose of each constant or variable where appropriate, and should line up under each other. For example, in the main function, we might declare: const int MAX_SIZE = 100; // Maximum size of array const double G = 9.8; // Gravitational constant m/s/s int main (int argc, char *argv[])
  • 6. { int i, // Outer loop index j, // Inner loop index tests[MAX_SIZE]; // Array of test scores Point p1; ... } // end main A statement should not be longer than a screen's width (about 80 characters). If a non-I/O, non-function call statement must be continued on more than one line, the second line should be indented to at least 6 spaces and successive continuation lines should be aligned with the second line of the statement. For example, we might write while ((('a' <= line [i]) && (line[i] <= 'z')) || (('A' <= line[i]) && (line[i] <= 'Z'))) i++; An I/O statement should be broken up so that the << or >> operators line up. For example, we might write cout << setw(15) << name << setw(30) << address << setw(15) << phone << endl; A long function call statement should be broken up so that the function arguments lined up. For example, we might write Sample (argument1, argument2, argument3, argument4, argument5, argument6); Whenever there is if, else, while, for, do, and switch, the curly braces should be used. They should line up under the first line for that statement. Each line of the body of a compound statement should be indented. should start on the next line and be indented. For example, if (first <= last) { found = true; } if (a [middle] = item) { item = a [middle]; found = true;
  • 7. position = middle; } // end if match found Column alignment should be observed for each set of reserved words if and else. This include multi- branch constructs, for example: if (x > 90) { grade = 'A'; } else if (x > 80) { grade = 'B'; } else if (x > 70) { grade = 'C'; } else if (x > 60) { grade = 'C'; } else { grade = 'D'; } Comments that describe one or more statements should be immediately above and aligned with the statement or collection of statements which they describe. There should be a blank line before such comments. For example, j = i; while ((j > 1) && (a [j - 1] > a [j])) { // a [1..j-1] is unsorted and a [j..i] sorted: Swap (a [j], a [j - 1]); j = j - 1 } // end while The main curly braces for functions should line up with the corresponding heading. For example, void FindMinIndex (...) {
  • 8. ... } // end FindMinIndex At least one space should be used in the following locations within C++ text (this does not apply within comments and character strings): ‱ before and after =, //, any relational, logical, arithmetic, or assignment operator ‱ before ( ‱ after a comma in argument lists, and after semicolon in for loop headings A function should fit on one screen (about 25 lines) if possible and must fit on a listing page (about 50 lines). Ideally, the analysis and design will not produce code that is more than a page long, but if the code does not fit initially, introduce one or more new functions to split up the work in logical places.