1. 程式人生 > >C語言程式碼規範(一)縮排與換行

C語言程式碼規範(一)縮排與換行

一、縮排的空格數為4個。

二、“{” 和 “}”各自獨佔一行。

    不規範例子:

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應該換行,讓“{”獨佔一行。

    規範的例子:

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((print_montion[0]!=SYS_PARAM.Motor_PARAM[0].Set_Speed)||(print_montion[1]!=SYS_PARAM.Motor_PARAM[1].Set_Speed))

    規範示例:

if( (print_montion[0] != SYS_PARAM.Motor_PARAM[0].Set_Speed) ||
    (print_montion[1] != SYS_PARAM.Motor_PARAM[1].Set_Speed) )

    換行後也要注意縮排對齊,使得排版整潔。

五、switch-case語句標準格式

    規範示例:

switch(variable)
{
    case value1:
        ...
        break;
    case value2:
        ...
        break;
    ...
    default:
        ...
        break;
}

六、if、for、do、while、case、switch、default語句獨佔一行,且if、for、do、while語句的執行語句部分無論多少都要加大括號"{}"。