Vous êtes sur la page 1sur 9

StyleGuide

CS50Manual(/)

TableofContents
Comments
Conditions
Switches
Functions
Indentation
Loops
for
while
dowhile
Pointers
Variables

Theresnoone,rightwaytostylizecode.Buttherearedefinitelyalotofwrong
(or,atleast,badways).Evenso,CS50doesaskthatyouadheretothe
conventionsbelowsothatwecanreliablyanalyzeyourcodesstyle.Similarly
docompaniestypicallyadopttheirown,companywideconventionsforstyle.

Comments
Commentsmakecodemorereadable,notonlyforothers(e.g.,yourTF)butalsoforyou,
especiallywhenhours,days,weeks,months,oryearspassbetweenwritingandreadingyour
owncode.Commentingtoolittleisbad.Commentingtoomuchisbad.Wheresthesweetspot?
Commentingeveryfewlinesofcode(i.e.,interestingblocks)isadecentruleofthumb.Tryto
writecommentsthataddressoneorbothofthesequestions:
1. Whatdoesthisblockdo?
2. WhydidIimplementthisblockinthisway?

Withinfunctions,use"inlinecomments"andkeepthemshort(e.g.,oneline),elseitbecomes
difficulttodistinguishcommentsfromcode,evenwithsyntaxhighlighting
(http://en.wikipedia.org/wiki/Syntax_highlighting).Noneedtowriteinfullsentences,butdo
leaveonespacebetweenthe // andyourcommentsfirstcharacter,asin:
//convertFahrenheittoCelsius
floatc=5.0/9.0*(f32.0);
Inotherwords,dontdothis:
//convertFahrenheittoCelsius
floatc=5.0/9.0*(f32.0);
Orthis:
//ConvertFahrenheittoCelsius.
floatc=5.0/9.0*(f32.0);
Atopyour.cand.hfilesshouldbemultilinecommentsthatsummarizewhatyourprogram(or
thatparticularfile)doesalongwith,perhaps,yournameandthatofthefile,asin:
/**
*hello.c
*
*DavidJ.Malan
*malan@harvard.edu
*
*Sayshellototheworld.
*/
Noticehow:
1. thefirstlinestartswith /**
2. thelastlineendswith */ and
3. alloftheasterisks( * )betweenthoselineslineupperfectlyinacolumn.
Atopeachofyourfunctions(except,perhaps, main ),meanwhile,shouldbemultiline
commentsthatsummarizewhatyourfunction,asin:

/**
*Returnsn^2(nsquared).
*/
intsquare(intn)
{
returnn*n;
}

Conditions
Conditionsshouldbestyledasfollows:
if(x>0)
{
printf("xispositive\n");
}
elseif(x<0)
{
printf("xisnegative\n");
}
else
{
printf("xiszero\n");
}
Noticehow:
1. thecurlybraceslineupnicely,eachonitsownline,makingperfectlyclearwhatsinsidethe
branch
2. theresasinglespaceaftereach if
3. eachcallto printf isindentedwith4spaces
4. therearesinglespacesaroundthe > andaroundthe > and
5. thereisntanyspaceimmediatelyaftereach ( orimmediatelybeforeeach ) .
Tosavespace,someprogrammersliketokeepthefirstcurlybraceonthesamelineasthe
conditionitself,butwedontrecommend,asitshardertoread,sodontdothis:

if(x<0){
printf("xisnegative\n");
}elseif(x<0){
printf("xisnegative\n");
}
Anddefinitelydontdothis:
if(x<0)
{
printf("xisnegative\n");
}
else
{
printf("xisnegative\n");
}

Switches
Declarea switch asfollows:
switch(n)
{
case1:
printf("nis1\n");
break;
case1:
printf("nis1\n");
break;
default:
printf("nisneither1nor1\n");
break;
}
Noticehow:
1. eachcurlybraceisonitsownline
2. theresasinglespaceafter switch

3. thereisntanyspaceimmediatelyaftereach ( orimmediatelybeforeeach )
4. theswitchscasesareindentedwith4spaces
5. thecases'bodiesareindentedfurtherwith4spacesand
6. each case (including default )endswitha break .

Functions
Besuretodefine main ,inaccordancewithC99(http://en.wikipedia.org/wiki/C99),with:
intmain(void)
{
}
Orwith:
intmain(intargc,char*argv[])
{
}
However,ifusingtheCS50Library(/library/),itsfinetodefine main with
intmain(intargc,stringargv[])
{
}
since string isjusta typedef (i.e.,synonym)for char* .
Donotdeclare main with:
intmain(intargc,char**argv)
{
}
orwith:

intmain()
{
}
orwith:
voidmain()
{
}
orwith:
main()
{
}
Asforyourownfunctions,besuretodefinethemsimiliarly,witheachcurlybraceonitsownline
andwiththereturntypeonthesamelineasthefunctionsname,justaswevedonewith main .

Indentation
Indentyourcodefourspacesatatimetomakeclearwhichblocksofcodeareinsideofothers.
IfyouuseyourkeyboardsTabkeytodoso,besurethatyourtexteditorsconfiguredtoconvert
tabs( \t )tofourspaces,elseyourcodemaynotprintordisplayproperlyonsomeoneelses
computer,since \t rendersdifferentlyindifferenteditors.(IfusingtheCS50Appliance
(/appliance/),itsfinetouseTabforindentation,ratherthanhittingyourkeyboardsspacebar
repeatedly,sincewevepreconfigured gedit andotherprogramstoconvert \t tofour
spaces.)Heressomenicelyindentedcode:

//printcommandlineargumentsoneperline
printf("\n");
for(inti=0;i<argc;i++)
{
for(intj=0,n=strlen(argv[i]);j<n;j++)
{
printf("%c\n",argv[i][j]);
}
printf("\n");
}

Loops
for
Wheneveryouneedtemporaryvariablesforiteration,use i ,then j ,then k ,unlessmore
specificnameswouldmakeyourcodemorereadable:
for(inti=0;i<LIMIT;i++)
{
for(intj=0;j<LIMIT;j++)
{
for(intk=0;k<LIMIT;k++)
{
//dosomething
}
}
}
Ifyouneedmorethanthreevariablesforiteration,itmightbetimetorethinkyourdesign!

while
Declare while loopsasfollows:
while(condition)
{
//dosomething
}

Noticehow:
1. eachcurlybraceisonitsownline
2. theresasinglespaceafter while
3. thereisntanyspaceimmediatelyafterthe ( orimmediatelybeforethe ) and
4. theloopsbody(acommentinthiscase)isindentedwith4spaces.

dowhile
Declare do...while loopsasfollows:
do
{
//dosomething
}
while(condition);
Noticehow:
1. eachcurlybraceisonitsownline
2. theresasinglespaceafter while
3. thereisntanyspaceimmediatelyafterthe ( orimmediatelybeforethe ) and
4. theloopsbody(acommentinthiscase)isindentedwith4spaces.

Pointers
Whendeclaringapointer,writethe * nexttothetype,asin:
int*p;
Dontwriteitnexttothevariablesname,asin:
int*p;
Thisconventioncanleadtoambiguityinsomecontexts,butwethink,overall,itsclearerwhen
firstlearningpointers.

Variables
BecauseCS50usesC99(http://en.wikipedia.org/wiki/C99),donotdefineallofyourvariablesat
theverytopofyourfunctionsbut,rather,whenandwhereyouactuallyneedthem.Moreover,
scopeyourvariablesastightlyaspossible.Forinstance,if i isonlyneededforthesakeofa
loop,declare i withintheloopitself:
for(inti=0;i<LIMIT;i++)
{
printf("%i\n",i);
}
Thoughitsfinetousevariableslike i , j ,and k foriteration,mostofyourvariablesshouldbe
morespecificallynamed.Ifyouresummingsomevalues,forinstance,callyourvariable sum .If
yourvariablesnamewarrantstwowords(e.g., is_ready ),putanunderscorebetweenthem,a
conventionpopularinCthoughlesssoinotherlanguages.
Ifdeclaringmultiplevariablesofthesametypeatonce,itsfinetodeclarethemtogether,asin:
intquarters,dimes,nickels,pennies;
Justdontinitializesomebutnotothers,asin:
intquarters,dimes=0,nickels=0,pennies;
Alsotakecaretodeclarepointersseparatelyfromnonpointers,asin:
int*p;
intn;
Dontdeclarepointersonthesamelineasnonpointers,lestitbeambiguousastowhetherthe
latterwasmeanttobetheformer,asin:
int*p,n;

Copyright2015,CS50

Vous aimerez peut-être aussi