#if
'#if
条件付きコンパイル
条件に合った部分の処理だけをコンパイル対象とする。
使い方
code:c
//**********************************************************
// 構文
#if 条件
//条件式1が成立するの時に実行する処理 (ブロック1)
何らかの処理
#elif 条件
// 条件式1が成立しないで条件2が成立する時の処理
何らかの処理
#else
//条件式1も条件式2も成立しない時の処理 (ブロック3)
何らかの処理
#endif
//**********************************************************
//**********************************************************
//if 0と1を切り替えることで、実行するプログラムの切り替えが出来る。  コメントアウトの代わりにもなる。
#if 0
//実行されない
#else
//実行される
#endif
#if 1
//実行される
#else
//実行されない
#endif
//**********************************************************
code:c
#ifdef //条件コンパイル:プログラムの中で不要な部分をカットする事が出来る。
//if(もし) def(#define)が定義されていたら、実行する
#include <stdio.h>
//#define DEBUG_ON
int main(void)
{
#ifdef DEBUG_ON
printf("Hello"); //#define DBUG_ONが無いため、実行されない。
#else
printf("World"); //実行される
#endif
return 0;
}
実行結果:https://paiza.io/projects/cW9PMMr4jmCJaFm7zd5bLw?language=c
code:c
#include <stdio.h>
#define DEBUG_ON
int main(void)
{
#ifdef DEBUG_ON //#define DBUG_ONがあるため、実行される。
printf("Hello");
#else
printf("World");
#endif
return 0;
}
code:c
/*
#define usb Disabelで、実行しない。Enableで実行するを決定するプログラム
*/
#define Disable 0xffff
#define Enable 0xfffe
#define usb0 Disable //usbをDisableに設定:実行しない
#define usb1 Enable //usb1をEnableに設定:実行する。
#include <stdio.h>
int main(void){
// Your code here!
#if usb0 == Enable //usb0がEnableの場合実行する。
printf("usb0は、Enable\n");
#endif
#if usb1 == Enable //usb1がEnableの場合実行する。
printf("usb1は、Enable\n");
#endif
}
実行結果:https://paiza.io/projects/bdsV2cUneBRnDzpyY70bXw
code:c
//#ifを使用して、処理を切り替えるプログラム
#define AD9 1
#define AD8 2
#define ADRSIZE AD9
//#define ADRSIZE AD8
#include <stdio.h>
int main(void){
// Your code here!
#if ADRSIZE == AD9 //AD9を実行
printf("AD9がEnable\n");
#endif
#if ADRSIZE == AD8 //AD8を実行
printf("AD8がEnable\n");
#endif
}
実行結果:https://paiza.io/projects/VIUtFfAedRwXKliWBBU4dg?language=c
code:c
#include <stdio.h>
int main(void){
// Your code here!
#if 1
printf("AD9がEnable\n");
#if 1
printf("AD8がEnable\n");
#endif
#endif
}
実行結果:https://paiza.io/projects/vIk2tzKkWQMSenWsHb2TwQ?language=c