Topic :
防止將function的參數作為工作variable。
Description :
將function的參數作為工作variable,有可能錯誤地改變參數內容,所以很危險。對必須改變的參數,最好先用local variable代之,最後再將該local variable的內容賦給該參數。
Example: /* #include<stdio.h> #define NUMBER 3 void bad_sum( unsigned int num, int *data, int *sum ){ unsigned int count; void good_sum( unsigned int num, int *data, int *sum ){ unsigned int count ; sum_temp = 0; void para_using(){ for(i=0; i<NUMBER; i++) } int main(int argc, char* argv[]){
* sample-73
*
* This sample shows how to use parameter in function.
*
* Avoid to use parameters, which is called by reference,
* as function local variable.
*
*/
*sum = 0;
for (count = 0; count < num; count++)
{
/* It is bad to calculate by "sum" */
*sum += data[count];
}
}
int sum_temp; /* Using a local variable to calculate */
for (count = 0; count < num; count ++)
{
sum_temp += data[count];
}
*sum = sum_temp;
}
int data[NUMBER];
int sum;
int i;
data[NUMBER]=i;
good_sum(NUMBER, data, &sum);
printf("sum : %d\n", sum);
para_using();
return 0;
}
沒有留言:
張貼留言