6、在可能的情况下使用typedef替代macro。当然有时候你无法避免macro,但是typedef更好。
typedef int* INT_PTR;
INT_PTR a , b;
# define INT_PTR int*;
INT_PTR a , b; |
在这个宏定义中,a是一个指向整数的指针,而b是只有一个整数声明。使用typedef a和b都是 整数的指针。
7、确保声明和定义是静态的,除非您希望从不同的文件中调用该函数。
在同一文件函数对其他函数可见,才称之为静态函数。它限制其他访问内部函数,如果我们希望从外界隐藏该函数。现在我们并不需要为内部函数创建头文件,其他看不到该函数。
静态声明一个函数的优点包括:
A)两个或两个以上具有相同名称的静态函数,可用于在不同的文件。
B)编译消耗减少,因为没有外部符号处理。
让我们做更好的理解,下面的例子:
/*first_file.c*/
static int foo ( int a )
{
/*Whatever you want to in the function*/
}
/*second_file.c*/
int foo ( int )
int main()
{
foo(); // This is not a valid function call as the function foo can only be called by any other function within first_file.c where it is defined.
return 0;
} |
8、使用Memoization,以避免递归重复计算
考虑Fibonacci(斐波那契)问题;Fibonacci问题是可以通过简单的递归方法来解决:
int fib ( n )
{
if ( n == 0 || n == 1 ) {
return 1;
}
else {
return fib( n - 2 ) + fib ( n - 1 );
}
} |
注:在这里,我们考虑Fibonacci 系列从1开始,因此,该系列看起来:1,1,2,3,5,8,...