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?

はじめに

この記事について

「C言語の基礎を学ぼう」をテーマに、自身の知識 + α をアドベントカレンダーにまとめます。
25日間でC言語をマスターしよう - Qiita Advent Calendar 2025 - Qiita

こんな方を対象としています

  • コンピュータがプログラムをどのように動かしているか知りたい/知らない方

  • プログラミングをしてみたい方

  • C言語初心者の方

キーワード

  • プリプロセッサ命令

  • #define

  • #ifdef #endif

説明

プリプロセッサ命令

プリプロセッサ命令 とは、コンパイルの前に処理される命令のことです。

プリプロセッサ命令は # で始まります。

#include もプリプロセッサ命令の1つです。
コンパイルの前に指定したヘッダファイルの内容を読み込みます。

#define

#define は文字列1を文字列2に置き換えます。

#define 文字列1 文字列2

定数を設定したり、 簡単な処理を定義した マクロ を設定することができます。

#include <stdio.h>
#define MAX_SIZE 100
int main(void) {
    int a[MAX_SIZE];
    char b[MAX_SIZE];
    printf("%d,%d", (int)sizeof(a), (int)sizeof(b));
    return 0;
}
400,100

引数をとることも可能です。

#include <stdio.h>
#define PRINT_INT(x, y, z) printf("%d,%d,%d", x, y, z)
int main(void) {
    int a = 5, b = 7, c = 3;
    PRINT_INT(a, b, c);
    return 0;
}
5,7,3

#ifdef #endif

特殊な条件時の処理を記載したいとき、 #ifdef#endif の間に処理を記述します。
#define でマクロを定義した場合、#ifdef #endif 間がコンパイルされます。

#define マクロ名 // マクロが定義されている
#ifdef マクロ名
  // コンパイルされる(実行される)
#endif
// マクロが定義されていない
#ifdef マクロ名
  // コンパイルされない(実行されない)
#endif

デバッグのための仕組みとして利用されることが多いです。

#include <stdio.h>
#define DEBUG
int main(void) {
    int a = 0;
    a++;
    #ifdef DEBUG
    printf("%d", a);
    #endif
    return 0;
}
1

練習

1. マクロを作成しよう

二乗マクロ SQUARE() と円の面積を求める CIRCLE_AREA() を作成しよう。

SQUARE(2) = 4
SQUARE(2 + 3) = 25
CIRCLE_AREA(2) = 12.566371
CIRCLE_AREA(2 + 3) = 78.539816

ポイント

マクロはコンパイル前に展開される点に注意します。
展開した文字列をコンパイルした際、想定した計算順序になるようにしましょう。

円周率は 3.1415926535 を使用しましょう。

解答例

#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define CIRCLE_AREA(r) ((r) * (r) * (3.1415926535))
int main(void) {
    printf("SQUARE(2) = %d\n", SQUARE(2));
    printf("SQUARE(2 + 3) = %d\n", SQUARE(2 + 3));
    printf("CIRCLE_AREA(2) = %f\n", CIRCLE_AREA(2));
    printf("CIRCLE_AREA(2 + 3) = %f\n", CIRCLE_AREA(2 + 3));
    return 0;
}
SQUARE(2) = 4
SQUARE(2 + 3) = 25
CIRCLE_AREA(2) = 12.566371
CIRCLE_AREA(2 + 3) = 78.539816

マクロの定義をする際、引数や演算のまとまりに必ず () を付けましょう。想定した計算順序にならない可能性があります。

#include <stdio.h>
#define SQUARE(x) x * x
int main(void) {
    // 2 + 3 * 2 + 3 = 2 + 6 + 3 = 11 になる
    printf("SQUARE(2 + 3) = %d\n", SQUARE(2 + 3));
    return 0;
}
SQUARE(2 + 3) = 11

おわりに

#define を使用することで、単なる数字や文字列、処理のまとまりに名前を付けることができます。
適切なマクロを作成すると保守しやすそうですね。

参考文献

↓↓↓ はじめてプログラミングを学んだときに読んだ本です ↓↓↓
詳細(プログラミング入門 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?