SlideShare a Scribd company logo
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.

More Related Content

PPT
Ch3 repetition
PDF
C programming course material
PPTX
C language 3
PPT
15 functions
PPT
Ch1 principles of software development
PPT
Ch4 functions
PPT
Ch2 introduction to c
DOCX
Forall & bulk binds
Ch3 repetition
C programming course material
C language 3
15 functions
Ch1 principles of software development
Ch4 functions
Ch2 introduction to c
Forall & bulk binds

What's hot (20)

PPTX
SAS Macro
PDF
Program slicing
PDF
DBMS 2011
PPTX
Programming in C Presentation upto FILE
DOC
C fundamental
PDF
Chapter 13.1.6
PPTX
Sample for Simple C Program - R.D.Sivakumar
PPT
User defined functions in C programmig
PPT
Savitch ch 04
PPTX
C language ppt
PPT
Lecture11 abap on line
PPTX
SAP Modularization techniques
PPTX
Basic syntax : Algorithm,Flow chart
PPTX
Functions in C
PDF
Passing table to subroutine
DOC
Complete list of all sap abap keywords
PPTX
Packages in PL/SQL
ODP
Open Gurukul Language PL/SQL
SAS Macro
Program slicing
DBMS 2011
Programming in C Presentation upto FILE
C fundamental
Chapter 13.1.6
Sample for Simple C Program - R.D.Sivakumar
User defined functions in C programmig
Savitch ch 04
C language ppt
Lecture11 abap on line
SAP Modularization techniques
Basic syntax : Algorithm,Flow chart
Functions in C
Passing table to subroutine
Complete list of all sap abap keywords
Packages in PL/SQL
Open Gurukul Language PL/SQL
Ad

Similar to Programming style guideline very good (20)

PPTX
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
PPTX
POLITEKNIK MALAYSIA
PPT
StandardsandStylesCProgramming
PPTX
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
PPT
Elementary_Of_C++_Programming_Language.ppt
PDF
Coding guideline
PPT
Lecture 2
PPTX
C STANDARDS (C17).pptx
PPTX
C STANDARDS (C17) (1).pptx
PPTX
C STANDARDS (C17) (1).pptx
PPTX
C STANDARDS (C17).pptx
PDF
Presentation
PPT
Coding
PPT
Pengaturcaraan asas
PPT
2.overview of c++ ________lecture2
PPT
73d32 session1 c++
PPTX
Programming Fundamental Slide lecture no.2 (Section E)
PPTX
Oop c++class(final).ppt
PPT
chapter-2.ppt
PPTX
Reading Notes : the practice of programming
Chapter vvxxxxxxxxxxx1 - Part 1 (3).pptx
POLITEKNIK MALAYSIA
StandardsandStylesCProgramming
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
Elementary_Of_C++_Programming_Language.ppt
Coding guideline
Lecture 2
C STANDARDS (C17).pptx
C STANDARDS (C17) (1).pptx
C STANDARDS (C17) (1).pptx
C STANDARDS (C17).pptx
Presentation
Coding
Pengaturcaraan asas
2.overview of c++ ________lecture2
73d32 session1 c++
Programming Fundamental Slide lecture no.2 (Section E)
Oop c++class(final).ppt
chapter-2.ppt
Reading Notes : the practice of programming
Ad

Recently uploaded (20)

DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Computing-Curriculum for Schools in Ghana
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
Cell Types and Its function , kingdom of life
PPTX
Lesson notes of climatology university.
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Cell Structure & Organelles in detailed.
Chinmaya Tiranga quiz Grand Finale.pdf
Computing-Curriculum for Schools in Ghana
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Supply Chain Operations Speaking Notes -ICLT Program
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Pharmacology of Heart Failure /Pharmacotherapy of CHF
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Pharma ospi slides which help in ospi learning
Abdominal Access Techniques with Prof. Dr. R K Mishra
Anesthesia in Laparoscopic Surgery in India
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Orientation - ARALprogram of Deped to the Parents.pptx
Yogi Goddess Pres Conference Studio Updates
Cell Types and Its function , kingdom of life
Lesson notes of climatology university.

Programming style guideline very good

  • 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.