C++ Reference Material Prgramming Style Cnventins What fllws here is a set f reasnably widely used C++ prgramming style cnventins. Whenever yu mve int a new prgramming envirnment, any cnventins yu have been using previusly may r may nt agree with the nes yu are required t use in the new envirnment, s yu shuld examine the new cnventins clsely t see what is the same, and what is different, frm what yu are used t. Fr the sake f brevity, nly a few specific examples t illustrate the style cnventins described here are given n this page, but many cde and frmatting examples are cllected in a series f separate cde examples. Yu shuld take the style cnventins yu are required t use very seriusly, because yur instructr and yur marker(s) (and, eventually, yur emplyer) will surely d s. Part A: Prgram Readability (Surce Cde Readability) The "Big Three" f Prgramming Style (accrding t Scbey) 1. Name things well, using the specified style cnventins. 2. Be cnsistent. 3. Frmat cntinually, and re-frmat whenever necessary. The imprtance f chsing a gd name fr each prgrammer-named entity, thereafter spelling and capitalizing that name apprpriately and cnsistently, and cntinuing t psitin these names prperly within well-frmatted cde, cannt be veremphasized. Rules fr naming and capitalizatin f prgrammer-chsen identifiers Naming 1. Names must be meaningful within their given cntext whenever pssible, which is mst f the time. Tw exceptins t this rule are: The use f single-letter lp cntrl variables such as i in thse situatins where n particular meaning attaches t the variable. Use f a generic variable name such as x fr reading in values (real numbers, say) t which n particular meaning applies. 2. Variables and value-returning functins are generally nun-like, as in: 3. length 4. numberofstudents
5. averagescre() Blean variables and functins, hwever, are usually adjective-like, as in: valid isfinished() Special (smetimes glbal, if permitted) blean variables that act as a switch t turn testing r debugging n r ff begin with the wrd testing r the wrd debugging, as apprpriate: testingtextitems r testingtextitemsglobal debuggingdisplayoutput r debuggingdisplayoutputglobal Appending the all-caps GLOBAL t indicate a variable acting glbally as a switch t turn testing r debugging n r ff is yet anther way t be as infrmative as pssible with a variable name. When ne is faced with the chice between lng variable names and clearer cde, r shrt variable names and less clear cde, the chice shuld be bvius. 6. The name f every vid functin (bth free functins and member functins) must begin with a verb, as in: 7. GetInputFrmUser() 8. DisplayOutput() 9. time.incrementhurs() 10. cunter.display() Occasinally value-returning functins may als begin with a verb. One particular example f this is any "getter" member functin that appears in a class: time.gethurs() Capitalizatin Names must always be capitalized cnsistently, accrding t whatever cnventins are being used fr each categry f name. Here are sme examples that illustrate ur capitalizatin cnventins: 1. Cnstants use all uppercase letters, with the wrds in multi-wrd names separated by underscres, as in: 2. cnst int SIZE = 100; 3. cnst duble TAX_RATE = 0.15; 4. Variables use "camel" ntatin, which means that names start with a lwercase letter, and all subsequent wrds in the name, if any, begin with an uppercase letter, as in:
5. duble cst; 6. int numberofguesses; 7. Macr definitins used in header files t avid multiple inclusin are a special case, and their capitalizatin is illustrated by this example fr a file (menu.h, say) cntaining the specificatin f a Menu class: 8. #ifndef MENU_H 9. #define MENU_H 10.... 11. #endif 12. Free functins start with a lwercase letter, except fr vid functins, which start with a capital letter (and, f curse, with a verb, as we pinted ut abve). Sme examples: 13. duble average(); 14. int numberofdigits(); 15. vid Swap(); 16. vid DisplayMenu(); 17. Member functins names always start with a lwercase letter, as in: 18. int time.gethurs(); 19. vid time.sethurs(); 20. vid time.display(); 21. Type names start with an uppercase letter, use the "camel" ntatin described abve, and names fr classes shuld be nuns that are usually singular (but nt always, as in TextItems}. Sme examples: 22. Menu 23. TextItems 24. RandmGeneratr 25. String80 Rules fr indentatin and alignment 1. Use an indentatin level f 4 spaces, and always use actual spaces, never the TAB character. 2. Indent and align each f the fllwing: a. Statements in the bdy f a functin (with respect t the crrespnding functin header) b. Statements in the bdy f a lp (with respect t the lp keywrd(s))
c. Statements in the bdy f an if and, if the else is present, in the bdy f the else (The statements in the bdy f an if shuld always align with thse in the bdy f the crrespnding else, and the if and else must themselves align, unless the entire if..else cnstruct is a shrt ne n a single line.) d. Field definitins in the definitin f a struct e. Member definitins in the definitin f a class 3. Each level f nesting requires anther level f indentatin. 4. Align enclsing braces vertically with each ther, except in very rare cases. [A shrt array initializatin cmes t mind as an exceptin.] Situatins where braces must be aligned vertically include: a. The braces enclsing a functin bdy with the functin header b. The braces enclsing a lp bdy in a while, d..while r fr lp c. The braces enclsing the bdy f an if, else r switch with the crrespnding if, else r switch d. The braces enclsing the bdy f a struct r class with the keywrd struct r class and with the access specifier(s) public, private and/r prtected (if present) 5. Align cmments with the thing cmmented (unless, f curse, it is an in-line cmment. 6. If a statement extends ver mre than ne line, indent and align the secnd and any subsequent lines fr readability (which may smetimes mean ignring the 4- space-indentatin rule fr thse lines). Use f whitespace 1. Use vertical spacing t enhance readability. Fr example, use ne r mre blank lines t separate lgically distinct parts f a prgram. In general, dn't be afraid t use mre vertical whitespace, rather than less. 2. Use hrizntal spacing t enhance readability. Fr example, it is usually a gd idea t place a blank space n each side f an peratr such as << r +, thugh this rule can be relaxed in a lng cmplex expressin where the enclsing spaces may be remved frm sme f the peratrs t shw mre clearly which perands are assciated with particular peratrs. A typical situatin where this might be dne is t use
3. fr (int i=start; i<=finish; i++)... rather than fr (int i = start; i <= finish; i++)... fr example, where it might be argued that the first is (in this case) slightly mre readable. 4. Sme prgrammers prefer t use a style that is almst "functinal" in nature in their writing f selectin and lping statements, by mitting the space between the selectin r lping keywrd and the fllwing left parenthesis, as in 5. if(cnditin)... 6. while(cnditin)... 7. fr(int i=0;... ) and s n. This is als permissible, but if used at all it must (f curse) be used cnsistently. Cmments 1. When cmmenting yur cde, yu shuld strive t be infrmative withut being excessive. Yur gal is t have readable cde, and t many cmments can ften be nearly as bad as, and smetimes wrse than, t few. 2. At the beginning f a file, always have a cmment cntaining the name f the file, and a cmment cntaining the purpse f the cde in that file. These tw cmments can ften be ne line each. Yu may als want, r need, additinal cmments in this lcatin, such as the cde authr's name, the date f the current versin, the current versin number, and perhaps even a list f mdificatins included in the current versin. Exactly what these initial cmments are t cntain will generally be determined by yur instructr, r the cding cnventins f yur emplyer. 3. Fr each functin, include the fllwing infrmatin in the given rder (and nte that in the case f class files, we require the infrmatin t be present in the specificatin (header) file, but we allw it t be mitted in the implementatin file, since the appearance f the same infrmatin in tw different lcatins generally leads t a maintenance nightmare): One r mre cmment statements describing in summary frm (r mre detailed frm if necessary) what the functin des. The return value f the functin.
A list f the functin's parameters in the same rder as they appear in the parameter list, with a descriptin f each. The functin's pre-cnditins and pst-cnditins. A list f any exceptins the functin may thrw, with a descriptin f each. In the actual parameter list f any functin, always place cmments (//in, //ut, r //inut) t indicate the cnceptual nature f each parameter with respect t the directin f infrmatin flw. Fr class member functins, these cmments must appear in bth the class header file and the class implementatin file. 4. Be sure t fllw whatever rules may be given fr inserting the necessary cmments int yur surce cde t identify crrectly any submissin fr evaluatin. This may require putting much f yur cmmenting in a frm required by sme kind f external dcumentatin-generatin system, such as Dxygen. If s, the details will be given elsewhere. Prgram Structure 1. When yur entire prgram is cntained in a single surce cde file, that file shuld have the structure btained by placing the fllwing cde sectins in the given rder: a. Cmments indicating the name f the file, purpse f the cde in that file, and anything else that may be required in these initial cmments fr the particular ccasin b. The necessary "includes" fr the required header files (Als, each grup f includes that requires a using declaratin r ne r mre using statements, must be fllwed by the necessary using declaratins/statements.) c. Definitins fr any glbal cnstants and glbal data types, and declaratins f any explicitly permitted glbal variables. d. Prttypes fr any required functins, gruped in sme intelligent way that will depend n the nature f the prgram. e. The main functin. f. Definitins fr each f the functins whse prttypes appeared befre main, and in the same rder as the crrespnding prttypes. 2. When yu have a multi-file prgram, each file shuld fllw the abve guidelines, except f curse that nly ne file will have a main functin in it, and functin prttypes are generally in a different file frm the crrespnding functin
definitins. The cntents f any ne file shuld frm a lgical gruping f sme kind within the cntext f the verall prgram. Maximum Length f Surce Cde Lines Chse a maximum length fr the lines f text in yur surce cde file in rder t ensure that yur lines f cde d nt "wrap" in an unsightly fashin, either n the screen r n the printed page. It is yur respnsibility t chse and insert gd line breaks t prevent this frm happening, while at the same time ensuring that yur cde remains as readable as pssible. A maximum line length value between 72 and 76 characters is recmmended, but whatever value yu chse must be stricly less than 80. N TAB Characters in Surce Cde Yur surce cde must nt cntain any TAB characters. Mst mdern editrs have an easy way t ensure that this requirement is met. Yu shuld find ut what the necessary prcedure is in yur case, and use it cnsistently. Having nly spaces in yur surce cde file means that its indentatin and aligment will remain the same, n matter where that file may be printed. Miscellaneus 1. Put each prgram statement n a separate line, unless yu can make a very gd argument t explain why yu didn't. One such argument might be that yu used a ne-line-but-multi-statement C++ "idim" f sme kind. 2. Use named cnstants whenever apprpriate. 3. Always prtect header files, and ther files t be included, against multiple inclusin. Part B: User Interface and Prgram Output Self-identificatin and prgrammer identificatin Each prgram shuld identify bth itself and its authr(s) when it runs. Exactly hw this is t be dne fr submissins fr evaluatin will be specified by yur instructr. Self-descriptin and/r n-line help Each prgram shuld at a minimum describe briefly what it des when it runs. Such infrmatin may appear autmatically when the prgram runs, in simple cases. In mre cmplex prgrams this infrmatin and much else may be available via an n-line help system f sme kind. Once again, fr submissins fr evaluatin, yur instructr will prvide details n the kind f infrmatin t be displayed.
Prmpting fr input Every prgram must prmpt prperly fr all input that it requires. Nte in particular that there shuld alwalys be a space at the end f prmpt (between the prmpt itself and the input entered in respnse t that prmpt) in thse situatins where the input is entered n the same line as the prmpt. Eching input in the utput It is always gd prgramming style t have a prgram ech its input smewhere in its utput, s the user can verify that what was thught t be entered was in fact entered. Organizatin and frmatting f utput All utput must be rganized, aligned, and frmatted fr maximum readability by the user. Spelling and punctuatin The appearance f misspellings and bad punctuatin in prgram utput is nt nly bad style, but is bund t raise questins in the mind f a user abut the care taken in ther aspects f prgram develpment.