2008-04-24

程式撰寫規範 [part 5]

Topic :

防止將function的參數作為工作variable。

Description :

將function的參數作為工作variable,有可能錯誤地改變參數內容,所以很危險。對必須改變的參數,最好先用local variable代之,最後再將該local variable的內容賦給該參數。

Example:

/*
* sample-73
*
* This sample shows how to use parameter in function.
*
* Avoid to use parameters, which is called by reference,
* as function local variable.
*
*/

#include<stdio.h>

#define NUMBER 3

void bad_sum( unsigned int num, int *data, int *sum ){

    unsigned int count;
           *sum = 0;
           for (count = 0; count < num; count++)
           {
        /* It is bad to calculate by "sum" */
            *sum += data[count];
           }
}

void good_sum( unsigned int num, int *data, int *sum ){

         unsigned int count ;
           int sum_temp;         /* Using a local variable to calculate */

           sum_temp = 0;
           for (count = 0; count < num; count ++)
           {
               sum_temp += data[count];
           }
           *sum = sum_temp;
}

void para_using(){
    int data[NUMBER];
    int sum;
    int i;

    for(i=0; i<NUMBER; i++)
        data[NUMBER]=i;
     good_sum(NUMBER, data, &sum);
    printf("sum : %d\n", sum);

}

int main(int argc, char* argv[]){
    para_using();
    return 0;
}

沒有留言:

張貼留言