每天學一點c++:#if #ifdef #ifndef #elif #else #endif的用法


#if, #ifdef, #ifndef, #else, #elif, #endif的用法:

    這些命令可以讓編譯器進行簡單的邏輯控制,當一個文件被編譯時,你可以用這些命令去決定某些代碼的去留,

  這些命令式條件編譯的命令。

常見的條件編譯的三種形式:

  ①第一種形式: 
    #if defined(或者是ifdef)<標識符(條件)> 

    <程序段1>

     [#else 
    <程序段2>] 

    #endif 
②第二種形式: 
    #if !defined(或者是ifndef)<標識符(條件)> 

    <程序段1> 

    [#else 
    <程序段2>] 

    #endif 
③第三種形式:

   #ifdef … 

  [#elif … ] 

  [#elif …] 

  #else …  

  #endif

示例:

#include <iostream>

using namespace std;

int main()
{
#if DEBUG  /*或者是#ifdef DEBUG*/
cout << "條件成立,DEBUG已經定義了!" <<endl;
#else
cout << "條件不成立,DEBUG還沒定義" <<endl;
#endif
return 0;
}

//結果輸出:條件不成立,DEBUG還沒定義

//如果是添加了#define DEBUG ,輸出結果是:條件成立,DEBUG已經定義了!

#include <iostream>
using namespace std;
#define DEBUG
int main()
{
#ifdef DEBUG /*或者是#ifdef DEBUG*/
cout << "條件成立,DEBUG已經定義了!" <<endl;
#else
cout << "條件不成立,DEBUG還沒定義" <<endl;
#endif
return 0;
}

//要注意的是,如果是#define 宏名,沒有宏體如 #define DEBUG,就必須使用#ifdef或#ifndef與之對應,

//如果是#define 宏名 宏體,如 #define NUM 1,#if 和#ifdef都可以使用。

/*

#define的用法:

 

*/

示例二:

#include <iostream>
using namespace std;

#define NUM  10

int main()
{
        #ifndef NUM
        cout << "NUM沒有定義!"<<endl;
        #elif NUM >= 100
        cout << "NUM >100" <<endl;
        #elif NUM <100 && NUM >10
        cout << "10 < NUM < 100" <<endl;
        #elif NUM == 10
        cout << "NUM ==10" <<endl;
        #else
        cout << "NUM < 10" << endl;
        #endif
        return 0;
}
//輸出NUM ==10

 

 

 

  

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM