int32_ta=sum(4,3);/*OK*/int32_ta=sum(4,3);/*Wrong*/
size_ti;for(i=0;i<5;++i){/*OK*/}for(i=0;i<5;++i){/*Wrong*/}for(i=0;i<5;++i)/*Wrong*/{}
//微信公众号:嵌入式大杂烩int32_ta;a=3+4;/*OK*/for(a=0;a<5;++a)/*OK*/a=3+4;/*Wrong*/a=3+4;/*Wrong*/for(a=0;a<5;++a)/*Wrong*/
//微信公众号:嵌入式大杂烩func_name(5,4);/*OK*/func_name(4,3);/*Wrong*/
staticint32_ta;/*OK*/staticint32_tb=4;/*OK*/staticint32_ta=0;/*Wrong*/voidmy_func(void){staticint32_t*ptr;/*OK*/staticcharabc=0;/*Wrong*/}
voidmy_func(void){chara;/*OK*/charb;/*Wrong,variablewithchartypealreadyexists*/chara,b;/*OK*/}
i.自定义结构和枚举
ii.整数类型,更宽的无符号类型优先
(相关资料图)
iii.单/双浮点
intmy_func(void){/*1*/my_struct_tmy;/*Firstcustomstructures*/my_struct_ptr_t*p;/*Pointerstoo*//*2*/uint32_ta;int32_tb;uint16_tc;int16_tg;charh;/*...*//*3*/doubled;floatf;}
/*OK*/for(size_ti=0;i<10;++i)/*OK,ifyouneedcountervariablelater*/size_ti;for(i=0;i<10;++i){if(...){break;}}if(i==10){}/*Wrong*/size_ti;for(i=0;i<10;++i)...
voida(void){/*Avoidfunctioncallswhendeclaringvariable*/int32_ta,b=sum(1,2);/*Usethis*/int32_ta,b;b=sum(1,2);/*Thisisok*/uint8_ta=3,b=4;}
/*OK*/uint8_tstatus;status=0;/*Wrong*/#include boolstatus=true;
void*ptr;/*...*//*OK,compareagainstNULL*/if(ptr==NULL||ptr!=NULL){}/*Wrong*/if(ptr||!ptr){}
int32_ta=0;...a++;/*Wrong*/++a;/*OK*/for(size_tj=0;j<10;++j){}/*OK*/
/*Whendcouldbemodified,datapointedtobydcouldnotbemodified*/voidmy_func(constvoid*d){}/*Whendanddatapointedtobydbothcouldnotbemodified*/voidmy_func(constvoid*constd){}/*Notrequired,itisadvised*/voidmy_func(constsize_tlen){}/*Whendshouldnotbemodifiedinsidefunction,onlydatapointedtobydcouldbemodified*/voidmy_func(void*constd){}
/**Tosenddata,functionshouldnotmodifymemorypointedtoby`data`variable*thus`const`keywordisimportant**Tosendgenericdata(ortowritethemtofile)*anytypemaybepassedfordata,*thususe`void*`*//*OKexample*/voidsend_data(constvoid*data,size_tlen){/*OK*//*Donotcast`void*`or`constvoid*`*/constuint8_t*d=data;/*Functionhandlespropertypeforinternalusage*/}voidsend_data(constvoid*data,intlen){/*Wrong,notnotuseint*/}
/*OK*/#include voidmy_func(size_tsize){int32_t*arr;arr=malloc(sizeof(*arr)*n);/*OK,Allocatememory*/arr=malloc(sizeof*arr*n);/*Wrong,bracketsforsizeofoperatoraremissing*/if(arr==NULL){/*FAIL,nomemory*/}free(arr);/*Freememoryafterusage*/}/*Wrong*/voidmy_func(size_tsize){int32_tarr[size];/*Wrong,donotuseVLA*/}
size_tlength=5;/*Countervariable*/uint8_tis_ok=0;/*Boolean-treatedvariable*/if(length)/*Wrong,lengthisnottreatedasboolean*/if(length>0)/*OK,lengthistreatedascountervariablecontainingmultivalues,notonly0or1*/if(length==0)/*OK,lengthistreatedascountervariablecontainingmultivalues,notonly0or1*/if(is_ok)/*OK,variableistreatedasboolean*/if(!is_ok)/*OK,-||-*/if(is_ok==1)/*Wrong,nevercomparebooleanvariableagainst1!*/if(is_ok==0)/*Wrong,use!fornegativecheck*/
注释
//Thisiscomment(wrong)/*Thisiscomment(ok)*/
/**Thisismulti-linecomments,*writtenin2lines(ok)*//***Wrong,usedouble-asteriskonlyfordoxygendocumentation*//**Singlelinecommentwithoutspacebeforeasterisk(wrong)*//**Singlelinecommentinmulti-lineconfiguration(wrong)*//*Singlelinecomment(ok)*/
voidmy_func(void){chara,b;a=call_func_returning_char_a(a);/*Thisiscommentwith12*4spacesindentfrombeginningofline*/b=call_func_returning_char_a_but_func_name_is_very_long(a);/*Thisiscomment,alignedto4-spacesindent*/}
函数
/*OK*/voidmy_func(void);voidmyfunc(void);/*Wrong*/voidMYFunc(void);voidmyFunc();
/*OK*/constchar*my_func(void);my_struct_t*my_func(int32_ta,int32_tb);/*Wrong*/constchar*my_func(void);my_struct_t*my_func(void);
/*OK,functionnamesaligned*/voidset(int32_ta);my_type_tget(void);my_ptr_t*get_ptr(void);/*Wrong*/voidset(int32_ta);constchar*get(void);
/*OK*/int32_tfoo(void){return0;}/*OK*/staticconstchar*get_string(void){return"Helloworld!\r\n";}/*Wrong*/int32_tfoo(void){return0;}
变量
/*OK*/int32_ta;int32_tmy_var;int32_tmyvar;/*Wrong*/int32_tA;int32_tmyVar;int32_tMYVar;
voidfoo(void){int32_ta,b;/*OK*/chara;charb;/*Wrong,chartypealreadyexists*/}
voidfoo(void){int32_ta;a=bar();int32_tb;/*Wrong,thereisalreadyexecutablestatement*/}
int32_ta,b;a=foo();if(a){int32_tc,d;/*OK,canddareinif-statementscope*/c=foo();int32_te;/*Wrong,therewasalreadyexecutablestatementinsideblock*/}
/*OK*/char*a;/*Wrong*/char*a;char*a;
/*OK*/char*p,*n;
结构、枚举类型定义
在声明结构体时,它可以使用以下三种不同的选项之一:
1、当结构体仅用名称声明时,它的名称后不能包含_t后缀。
structstruct_name{char*a;charb;};
2、当只使用typedef声明结构时,它的名称后面必须包含_t后缀。
typedefstruct{char*a;charb;}struct_name_t;
3、当结构用name和typedef声明时,它不能包含_t作为基本名称,它必须在它的名称后面包含_t后缀作为typedef部分。
typedefstructstruct_name{char*a;charb;charc;}struct_name_t;
错误声明的例子及其建议的纠正:
/*aandbmustbeseparatedto2lines*//*Nameofstructurewithtypedefmustinclude_tsuffix*/typedefstruct{int32_ta,b;}a;/*Correctedversion*/typedefstruct{int32_ta;int32_tb;}a_t;/*Wrongname,itmustnotinclude_tsuffix*/structname_t{int32_ta;int32_tb;};/*Wrongparameters,mustbealluppercase*/typedefenum{MY_ENUM_TESTA,my_enum_testb,}my_enum_t;
/*OK*/a_ta={.a=4,.b=5,};/*Wrong*/a_ta={1,2};
/*Functionaccepts2parametersandreturnsuint8_t*//*Nameoftypedefhas`_fn`suffix*/typedefuint8_t(*my_func_typedef_fn)(uint8_tp1,constchar*p2);
复合语句
/*OK*/if(c){do_a();}else{do_b();}/*Wrong*/if(c)do_a();elsedo_b();/*Wrong*/if(c)do_a();elsedo_b();
/*OK*/if(a){}elseif(b){}else{}/*Wrong*/if(a){}else{}/*Wrong*/if(a){}else{}
/*OK*/do{int32_ta;a=do_a();do_b(a);}while(check());/*Wrong*/do{/*...*/}while(check());/*Wrong*/do{/*...*/}while(check());
if(a){do_a();}else{do_b();if(c){do_c();}}
if(a)do_b();elsedo_c();if(a)do_a();elsedo_b();
/*OK*/while(is_register_bit_set()){}/*Wrong*/while(is_register_bit_set());while(is_register_bit_set()){}while(is_register_bit_set()){}
/*Waitforbittobesetinembeddedhardwareunituint32_t*addr=HW_PERIPH_REGISTER_ADDR;/*Waitbit13tobeready*/while(*addr&(1<<13)){}/*OK,emptyloopcontainsnospacesinsidecurlybrackets*/while(*addr&(1<<13)){}/*Wrong*/while(*addr&(1<<13)){/*Wrong*/}while(*addr&(1<<13));/*Wrong,curlybracketsaremissing.Canleadtocompilerwarningsorunintentionalbugs*/
/*Notrecommended*/int32_ta=0;while(a<10){......++a;}/*Better*/for(size_ta=0;a<10;++a){}/*Better,ifincmaynothappenineverycycle*/for(size_ta=0;a<10;){if(...){++a;}}
分支语句
/*OK,everycasehassingleindent*//*OK,everybreakhasadditionalindent*/switch(check()){case0:do_a();break;case1:do_b();break;default:break;}/*Wrong,caseindentmissing*/switch(check()){case0:do_a();break;case1:do_b();break;default:break;}/*Wrong*/switch(check()){case0:do_a();break;/*Wrong,breakmusthaveindentasitisundercase*/case1:do_b();/*Wrong,indentundercaseismissing*/break;default:break;}
/*OK*/switch(var){case0:do_job();break;default:break;}/*Wrong,defaultismissing*/switch(var){case0:do_job();break;}
switch(a){/*OK*/case0:{int32_ta,b;charc;a=5;/*...*/break;}/*Wrong*/case1:{int32_ta;break;}/*Wrong,breakshallbeinside*/case2:{int32_ta;}break;}
宏和预处理指令
/*OK*/#defineMY_MACRO(x)((x)*(x))/*Wrong*/#definesquare(x)((x)*(x))
/*OK*/#defineMIN(x,y)((x)<(y)?(x):(y))/*Wrong*/#defineMIN(x,y)x
/*Wrong*/#defineMIN(x,y)(x)<(y)?(x):(y)#defineSUM(x,y)(x)+(y)/*ImagineresultofthisequationusingwrongSUMimplementation*/int32_tx=5*SUM(3,4);/*Expectedresultis5*7=35*/int32_tx=5*(3)+(4);/*Itisevaluatedtothis,finalresult=19whichisnotwhatweexpect*//*Correctimplementation*/#defineMIN(x,y)((x)<(y)?(x):(y))#defineSUM(x,y)((x)+(y))
typedefstruct{int32_tpx,py;}point_t;point_tp;/*Definenewpoint*//*Wrongimplementation*//*Definemacrotosetpoint*/#defineSET_POINT(p,x,y)(p)->px=(x);(p)->py=(y)/*2statements.Lastoneshouldnotimplementsemicolon*/SET_POINT(&p,3,4);/*Setpointtoposition3,4.Thisevaluatesto...*/(&p)->px=(3);(&p)->py=(4);/*...tothis.Inthisexamplethisisnotaproblem.*//*Considerthisuglycode,howeveritisvalidbyCstandard(notrecommended)*/if(a)/*Ifaistrue*/if(b)/*Ifbistrue*/SET_POINT(&p,3,4);/*Setpointtox=3,y=4*/elseSET_POINT(&p,5,6);/*Setpointtox=5,y=6*//*Evaluatestocodebelow.Doyouseetheproblem?*/if(a)if(b)(&p)->px=(3);(&p)->py=(4);else(&p)->px=(5);(&p)->py=(6);/*Orifwerewriteitalittle*/if(a)if(b)(&p)->px=(3);(&p)->py=(4);else(&p)->px=(5);(&p)->py=(6);/**Askyourselfaquestion:Towhich`if`statement`else`keywordbelongs?**Basedonfirstpartofcode,answerisstraight-forward.Toinner`if`statementwhenwecheck`b`condition*Actualanswer:Compilationerroras`else`belongsnowhere*//*Betterandcorrectimplementationofmacro*/#defineSET_POINT(p,x,y)do{(p)->px=(x);(p)->py=(y);}while(0)/*2statements.Nosemicolonafterwhileloop*//*Orevenbetter*/#defineSET_POINT(p,x,y)do{\/*Backslashindicatesstatementcontinuesinnewline*/(p)->px=(x);\(p)->py=(y);\}while(0)/*2statements.Nosemicolonafterwhileloop*//*Noworiginalcodeevaluatesto*/if(a)if(b)do{(&p)->px=(3);(&p)->py=(4);}while(0);elsedo{(&p)->px=(5);(&p)->py=(6);}while(0);/*Everypartof`if`or`else`containsonly`1`innerstatement(do-while),hencethisisvalidevaluation*//*Tomakecodeperfect,usebracketsforeveryif-ifelse-elsestatements*/if(a){/*Ifaistrue*/if(b){/*Ifbistrue*/SET_POINT(&p,3,4);/*Setpointtox=3,y=4*/}else{SET_POINT(&p,5,6);/*Setpointtox=5,y=6*/}}
/*OK*/#ifdefined(XYZ)#ifdefined(ABC)/*dowhenABCdefined*/#endif/*defined(ABC)*/#else/*defined(XYZ)*//*DowhenXYZnotdefined*/#endif/*!defined(XYZ)*//*Wrong*/#ifdefined(XYZ)#ifdefined(ABC)/*dowhenABCdefined*/#endif/*defined(ABC)*/#else/*defined(XYZ)*//*DowhenXYZnotdefined*/#endif/*!defined(XYZ)*/
文档
文档化的代码允许doxygen解析和通用的html/pdf/latex输出,因此正确地执行是非常重要的。
/***\briefHoldspointertofirstentryinlinkedlist*Beginningofthistextis5tabs(20spaces)frombeginningofline*/statictype_t*list;
/***\briefThisispointstruct*\noteThisstructureisusedtocalculateallpoint*relatedstuff*/typedefstruct{int32_tx;/*!
/***\briefSum`2`numbers*\param[in]a:Firstnumber*\param[in]b:Secondnumber*\returnSumofinputvalues*/int32_tsum(int32_ta,int32_tb){returna+b;}/***\briefSum`2`numbersandwriteittopointer*\noteThisfunctiondoesnotreturnvalue,itstoresittopointerinstead*\param[in]a:Firstnumber*\param[in]b:Secondnumber*\param[out]result:Outputvariableusedtosaveresult*/voidvoid_sum(int32_ta,int32_tb,int32_t*result){*result=a+b;}
/***\briefMyenumeration*/typedefenum{MY_ERR,/*!
/***\briefGetdatafrominputarray*\param[in]in:Inputdata*\returnPointertooutputdataonsuccess,`NULL`otherwise*/constvoid*get_data(constvoid*in){returnin;}
/***\briefGetminimalvaluebetween`x`and`y`*\param[in]x:Firstvalue*\param[in]y:Secondvalue*\returnMinimalvaluebetween`x`and`y`*\hideinitializer*/#defineMIN(x,y)((x)<(y)?(x):(y))
头/源文件
/***\filetemplate.h*\briefTemplateincludefile*//*Hereisemptyline*/
/***\filetemplate.h*\briefTemplateincludefile*//**Copyright(c)yearFirstNameLASTNAME**Permissionisherebygranted,freeofcharge,toanyperson*obtainingacopyofthissoftwareandassociateddocumentation*files(the"Software"),todealintheSoftwarewithoutrestriction,*includingwithoutlimitationtherightstouse,copy,modify,merge,*publish,distribute,sublicense,and/orsellcopiesoftheSoftware,*andtopermitpersonstowhomtheSoftwareisfurnishedtodoso,*subjecttothefollowingconditions:**Theabovecopyrightnoticeandthispermissionnoticeshallbe*includedinallcopiesorsubstantialportionsoftheSoftware.**THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,*EXPRESSORIMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIES*OFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSE*ANDNONINFRINGEMENT.INNOEVENTSHALLTHEAUTHORSORCOPYRIGHT*HOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHERLIABILITY,*WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISING*FROM,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOR*OTHERDEALINGSINTHESOFTWARE.**Thisfileispartoflibrary_name.**Author:FirstNameLASTNAME*/
/*file.h...*/#ifndef...externint32_tmy_variable;/*Thisisglobalvariabledeclarationinheader*/#endif/*file.c...*/int32_tmy_variable;/*Actuallydefinedinsource*/
/*Licensecomeshere*/#ifndefTEMPLATE_HDR_H#defineTEMPLATE_HDR_H/*Includeheaders*/#ifdef__cplusplusextern"C"{#endif/*__cplusplus*//*Filecontenthere*/#ifdef__cplusplus}#endif/*__cplusplus*/#endif/*TEMPLATE_HDR_H*/
本文来源网络,免费传达知识,版权归原作者所有。如涉及作品版权问题,请联系我进行删除。
往期推荐
《嵌入式Linux驱动大全》
谈谈嵌入式软件的兼容性!