一、縮進的空格數為4個。最好配置代碼編輯器將TAB鍵設置為空格替換,避免出現另一個編輯器打開時格式變亂的情況。
例如Notepad++設置
KEIL設置
二、“{” 和 “}”各自獨占一行。
? ? 不規范例子:
for(i = 0; i < student_num; i++)
{ if((score[i] >= 0) && (score[i]) <= 100)total_score += score[i];elseprintf(" error! score[%d] = %d\n", i, score[i]);
}
? ? 其中if應該換行,讓“{”獨占一行。
? ? 規范的例子:
for(i = 0; i < student_num; i++)
{ if((score[i] >= 0) && (score[i]) <= 100){total_score += score[i];}else{printf(" error! score[%d] = %d\n", i, score[i]);}
}
? ?
三、 當if的判斷和執行句子較短時,也需要換行。
? ? 不規范如下格式:
if(student_num > 100)i = 0;
? ? 規范示例:
if(student_num > 100)
{i = 0;
}
四、if判斷內容較長,可以考慮換行提高可閱讀性
? ? 不規范例子:
if((print_montion[0]!=SYS_PARAM.Motor_PARAM[0].Set_Speed)||(print_montion[1]!=SYS_PARAM.Motor_PARAM[1].Set_Speed))
if((M_rise && M_rise_temp)||(M_stretch && M_stretch_temp)||(M_revolve && M_revolve_temp))break;
? ? 規范示例:
if( (print_montion[0] != SYS_PARAM.Motor_PARAM[0].Set_Speed) ||(print_montion[1] != SYS_PARAM.Motor_PARAM[1].Set_Speed) )
if( (M_rise && M_rise_temp) ||(M_stretch && M_stretch_temp) ||(M_revolve && M_revolve_temp) )
{break;
}
? ? 換行后也要注意縮進對齊,使得排版整潔。
五、switch-case語句標準格式
? ? 規范示例:
switch(variable)
{case value1:...break;case value2:...break;...default:...break;
}
六、if、for、do、while、case、switch、default語句獨占一行,且if、for、do、while語句的執行語句部分無論多少都要加大括號"{}"。
七、嚴禁橫向代碼!!!
不規范示例:
if ( M_rise ) {EN_s = Enable; TIM_CCxNCmd(TIM1,TIM_Channel_1, ENABLE); }
if ( M_stretch ){EN_q = Enable; TIM_CCxNCmd(TIM1,TIM_Channel_2, ENABLE); }
if ( M_revolve ){EN_x = Enable; TIM_CCxNCmd(TIM1,TIM_Channel_3, ENABLE); }
修改:(這里的例子命名不規范,大家不要學)
if(M_rise){EN_s = Enable; TIM_CCxNCmd(TIM1, TIM_Channel_1, ENABLE); } if(M_stretch){EN_q = Enable; TIM_CCxNCmd(TIM1, TIM_Channel_2, ENABLE); } if(M_revolve){EN_x = Enable; TIM_CCxNCmd(TIM1, TIM_Channel_3, ENABLE); }
不要非主流自創風格,記住代碼是給別人讀的!