| 情報学部 | 菅沼ホーム | 全体目次 | 演習解答例 | 付録 | 索引 |
プリプロセッサに対する命令(疑似命令,#define 等のこと)は,区切りにセミコロンを使用せず,1 つの命令は 1 行に書く必要があります.
#define 識別子 文字列 #define 識別子([パラメータリスト]) 文字列
#define PI 3.14159265
#define SQUARE(arg) ((arg) * (arg))
/****************************/
/* 記号定数とマクロの定義 */
/* coded by Y.Suganuma */
/****************************/
#include <stdio.h>
#define CON 10
#define SIKI(v1, v2) (CON * v1 + v2) // 10 * x + y の定義
#define rep(i, k, n) for (int i = k; i <= n; i++) // for 文
int main()
{
int x = CON;
int y = SIKI(2, 5);
int s = 0;
rep(i, 1, 5)
s += i;
printf("x %d y %d s %d\n", x, y, s);
return 0;
}
x 10 y 25
#undef 識別子
#if 定数式 [文1] [#else 文2] #endif
/************************************/
/* 記号定数の定義による出力先の変更 */
/* coded by Y.Suganuma */
/************************************/
#include <stdio.h>
#define OUT "data"
int main()
{
int x[3] = {1, 2, 3};
FILE *stream;
/*
ケース1
*/
#if defined OUT /* OUTが定義,#ifdef OUT でも同じ*/
stream = fopen(OUT, "w");
fprintf(stream, "%d %d %d\n", x[0], x[1], x[2]);
printf("データはファイル「data」に出力されました\n");
#else /* OUTが未定義 */
printf("%d %d %d\n", x[0], x[1], x[2]);
#endif
/* OUTの定義解除 */
#undef OUT
/*
ケース2
*/
#if !defined OUT /* OUTが未定義,#ifndef OUT でも同じ*/
printf("%d %d %d\n", x[0], x[1], x[2]);
#else /* OUTが定義 */
stream = fopen(OUT, "w");
fprintf(stream, "%d %d %d\n", x[0], x[1], x[2]);
printf("データはファイル「data」に出力されました\n");
#endif
return 0;
}
/**************************************************/
/* 記号定数の定義・未定義により単位変換の方向変更 */
/* coded by Y.Suganuma */
/**************************************************/
#include <stdio.h>
#define DEG
#if defined DEG
#define UC 0.017453292
#else
#define UC 57.29577951
#endif
int main()
{
double x = 90.0;
double y = x * UC;
#if defined DEG /* 度からラジアン */
printf("%f 度は %f ラジアンです\n", x, y);
#else /* ラジアンから度 */
printf("%f ラジアンは %f 度です\n", y, x);
#endif
return 0;
}
#include "ファイル名" #include <ファイル名> // 一般に,システムによって準備されたファイルを使用する場合
#define PI 3.141592654 #define UC 0.017453292
/****************************/
/* ファイルの組み込み */
/* coded by Y.Suganuma */
/****************************/
#include <stdio.h>
#include "ang.h"
int main()
{
double x = PI;
double y = UC;
printf("x %f y %f\n", x, y);
return 0;
}
| 情報学部 | 菅沼ホーム | 全体目次 | 演習解答例 | 付録 | 索引 |