以下說明,在C 語言中,#if、#ifdef和#if defined 的區別。
看以下三個例子:
//範例(1) #include <stdio.h> #define NUM 10 int main() { #if NUM == 10 || NUM == 20 printf("NUM: %d\n", NUM); #else printf("NUM Error\n"); #endif }
根據範例(1),可以知道#if 後面接的define,需要明確定義其值。如#define NUM 10,明確定義NUM為10。
//範例(2) #include <stdio.h> #define NUM1 10 #define NUM2 int main(){ #if (defined(NUM1) && defined(NUM2)) printf("NUM1: %d\n", NUM1); printf("defined NUM2\n"); #else printf("Error\n"); #endif return 0; }
根據範例(2),可以知道#if defined 後面接的define,不需要明確定義其值。如例子中,NUM1 有定義為10,而NUM2 沒有定義值。再則,#if defined,可以使用運算子&& 或|| 做更進一步的使用。
//範例(3) #include <stdio.h> #define NUM1 int main(){ #ifdef NUM1 printf("defined NUM1\n"); #else printf("Error\n"); #endif return 0; }
根據範例(3),可以知道#ifdef 其實就是#if defined 的縮寫。最大差別,就在於#if defined 可以使用&& 或|| 做更進一步的使用,但#ifdef 不行。