LoginSignup
1
1

More than 1 year has passed since last update.

【C】初めてのC言語(24. 条件付きコンパイル - その2)

Posted at

はじめに

前回の「defineとifdef~endifを用いた条件付きコンパイル」に続いて、 @nagisep さんから教えて頂いた「if defined」を用いた条件付きコンパイルについて学んだ結果をまとめてみました。

学習環境

  • 今回はpaiza.ioのC言語のエディタを使いました。

if definedを使った例

  • if definedを使った方が、より柔軟に条件分岐できるようです。
    • ifdefだとif~else節しか使えないようですが...
    • if definedだと、if~else if~else節が使えるので、複数のシンボル(※以下の例だとFOOとBAR)を使った条件分岐を実現できます。
  • if definedの場合は、AND(&&)とOR(||)で複数の条件を使うことができます。
    • @nagisep さんも指摘されていましたが、これはifdefには無い機能なので、if definedの方が便利な感じがします。
Main.c
#include <stdio.h>

#define FOO
#define BAR

int main(void){
#if defined(FOO) && ! defined(BAR)
    printf("FOO\n");
#elif ! defined(FOO) && defined(BAR)
    printf("BAR\n");
#else
    printf("FOO BAR\n");
#endif
}
実行結果
FOO BAR

補足:これまでの学習の歩み

参考URL

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1