0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Cの基本11 ~条件付きコンパイル・その他の前処理指令~ 備忘録

Last updated at Posted at 2023-02-24

はじめに

私は初心者である。この備忘録を参考にされようとしている他の初心者の方は、ここに書かれていることを鵜呑みになさらぬようお願いしたい。何か間違いを見つけた方はコメント欄でご報告頂きたい。


条件付きコンパイル

条件付きコンパイルは、条件によってソースファイルの一部をコンパイルをしたり、コンパイルの対象から外したりする機能らしい。

条件付きコンパイルは #if指令,#else指令、#endif指令がある
形としてこんな感じらしい。

Program A
#if condition C
    Program X
#else
    Program Y
#endif
    Program B

Condition Cの真偽によって前処理の結果が変わるという具合だ。条件には整数の定数式を書く。0なら偽、1なら真となる。その条件式の値は前処理の時点で決まらなくてはならない。でないと全処理において真偽が判断できない。そりゃそうだ。

defined演算子と#ifdef#ifndef

条件式には普通の演算子の他に、単項演算子definedが使える。
defined(マクロ名)とした時、そのマクロが定義されてれば1、定義されてなければ0を与えるそうだ。
以前ここで対面した。

# if defined (マクロ名)

これは #ifdef指令を用いて

#ifdef マクロ名とも書ける。
________________________

#if !defined (マクロ名)

は#ifndef指令を使って

#ifndef マクロ名 とも書けるそうだ。

例題がこんな感じ

#include <stdio.h>

int main(void){
    #ifdef __STDC__
        printf("Standard C\n");
        # ifdef __STDC_VERSION__
            printf("Version %ld\n", __STDC_VERSION__);
        #else
            printf("Version Unknown");
        #endif
    #else 
        prinf("Not a standard C\n");
    #endif      
        return 0;
        
}

出力が

Standard C
Version 201710

演習にあった問題
マクロIsMorningが真ならGood Morning
偽ならGood Nightと表示するプログラムを作る

私がやったミスは以下。

#include <stdio.h>
// #define IsMorning 0

int main(void){
    #ifdef IsMorning
        printf("Good Morning\n");
    #else
        printf("Good Night\n");
    #endif
    return 0;
}    // 出力はGood Morning

私はここで、IsMorningの値が偽なのになぜMorningなのかと思ったが、それはdefined演算子を使っているからだった。
defined演算子はマクロが定義されているかどうかを見る。中の値は関係ない。
正しくは以下か。

#include <stdio.h>
#define IsMorning 0

int main(void){
    #if IsMorning == 1
        printf("Good Morning\n");
    #else
        printf("Good Night\n");
    #endif
    return 0;
}    // 出力はNightのほう

その他の前処理指令

他の前処理指令を列挙する。

  • #error指令 わざとエラーを起こす
  • #line指令 現在の行番号とファイル名を設定する
  • #pragma指令 処理系特有の動作を指定する

P370 必要になったら調べよう。


次はやっと配列とポインタだ

今回の内容は富永和人氏の新しいC言語の教科書を参考に書き留めてます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?