C前置處理

  • 69
  • 0
  • 2017-05-04

C前置處理

前置處理可以出現在程式任何地方,習慣在main主函式的前面。

前置處理的有效範圍是從指引所在處開始,一直到程式結束為止,除非使用  #undef  。

前置處理包含 :

  • 檔案含入 : #include
  • 字串置換 / 巨集定義 : #define、#undef
  • 條件編譯 : #if ... #elif ... #else ... #endif,#ifdef(#ifndef) ... #else ... #endif

Example :

#include "xxx" :系統會到目前的目錄尋找指定的檔案,否則到系統設定的目錄找

#include <xxx> :系統會到系統設定目錄找尋檔案

def.h ---------------

    #define pi 3.14

    #define a10

    #define b 20

----------------------

程式 :

#include <stdio.h>

#include "def.h"

void main(){

    printf("PI=%f\n",pi);

    printf("a+b=%d\n",a+b);

}

----------------------

執行結果 :

PI=3.14

a+b=30

----------------------

巨集使用

#define pi 3.14

#define add(a,b) a+b

#define hello_string "hello world"

another -----------------------------

#include < stdio.h >

#define  compare(a,b)   \
            if ( a > b )           \
              printf("a > b");  \
            else                    \
              if ( a < b )         \
                printf("a < b");\
              else                  \
                printf("a = b");
 
      void main(void)
          {
             int a,b;
             a=5;
             b=10;
             compare(a,b);
          }
 
   執行結果 :
              a < b

--------------------------------------

#include < stdio.h >

#define TURBOC
   
void main(void)
    {
     #ifdef TURBOC
        printf("Borland C compiler.\n");
     #endif
 
     #undef TURBOC
 
     #ifndef TURBOC
         printf("MircoSoft C compiler.\n");
     #endif
    }
 
執行結果 :
        Borland C compiler.
        MircoSoft C compiler.

 

 

 

 

< 興趣很難發覺,只有多方嘗試 >

                       - 這裡紀錄著我的心路歷程,每一篇文章都代表著進步

分享不錯的練習平台  https://www.codingame.com/

一起進步吧