1. 程式人生 > >C語言類函式巨集和一般函式的區別

C語言類函式巨集和一般函式的區別

類函式巨集:function-like-macro 用#define使用引數來定義巨集,巨集的引數用圓括號括起來,可以使一個引數或者多個引數,然後在使用的過程中這些引數將會被替換。

例如:

#define SQUARE(X) X*X //定義類函式巨集
z = SQUARE(3); //使用類函式巨集
原始碼:
[[email protected] test]# cat test.c
#include <stdio.h>
#define SQUARE(X) X*X
int squ_fun(int);
int main(void)
{
    int x = 0;
    printf("Please input one integer(n), and square(n+1) will be shown via two \
ways(function-like macro and general function). The default is 0.\n");
    scanf("%d", &x);
    printf("Evaluating SQUARE(3) is: %d \n", SQUARE(x+1));
    printf("Evaluating squ_fun(3) is: %d \n", squ_fun(x+1));
    return 0;
}

int squ_fun(int i)
{
    int z = 0;
    z = i * i;
    return z;
}
編譯&執行:
[[email protected] test]# gcc test.c
[[email protected] test]# ./a.out
Please input one integer(n), and square(n+1) will be shown via two ways(function-like macro and general function). The default is 0.
3
Evaluating SQUARE(3) is: 7
Evaluating squ_fun(3) is: 16
類函式巨集只會做字串替換(巨集定義都只會做字串替換),替換後為3+1*3+1,結果就是7;而一般函式就會把引數帶進函式進行計算後返回結果,這裡其實就是(3+1)*(3+1)。