1. 程式人生 > >C語言程式設計--巨集和預處理

C語言程式設計--巨集和預處理

C語言巨集



巨集定義常量


#include <stdio.h>

#define SIZE 100
#define BANNER "WARNING:"

int main(void){
    printf("%d\n", SIZE);
    printf("%s\n",BANNER);
    return 0;
}

巨集定義資料型別


#include <stdio.h>

#define string char*

int main(void){
    string banner = "HELLO, WORLD!";
    printf("%s\n",banner);
    return 0;
}

巨集定義函式


#include <stdio.h>
#include <stdlib.h>

#define random (rand()%100)

int main(void){
    while(1){
        int num = random;
        printf("%d\n", num);
        if (num >= 50){
            break;
        }
    }
    return 0;
}

巨集定義帶引數函式


#include <stdio.h>
#include <stdlib.h>

#define max(a,b) a>b?a:b

int main(void){
    int max_num;
    max_num = max(10,100);
    printf("%d\n",max_num);
    max_num = max(10,6);
    printf("%d\n",max_num);
    return 0;
}

巨集解除定義


#undef xxx

預處理



三個已知

#include <stdio.h>//包含檔案
#define SIZE 100 //定義巨集
#undef SIZE  //解除巨集定義

條件巨集定義


#define MAX 100
#ifdef MAX //如果定義了MAX巨集
    #undef MAX
#else //否則
    #define MAX 10
#endif
#ifndef MIN//如果沒有定義MIN
    #define MIN 2//定義巨集MIN為2
#endif

另外的條件判斷


#include <stdio.h>
#include <stdlib.h>

#define MAX_THREAD 10
#if MAX_THREAD > 5
    #undef MAX_THREAD
    #define MAX_THREAD 5
#endif


int main(void){
    printf("%d\n",MAX_THREAD);
    return 0;
}
/*同理#else和#elif的用法與else 和else if類似*/

最後兩個


/*
#error  當遇到標準錯誤時,輸出錯誤訊息
#pragma 使用標準化方法,向編譯器釋出特殊的命令到編譯器中
*/